Skip to content

Commit ba14199

Browse files
authored
Merge pull request bradtraversy#10 from rooky1905/master
Added Encapsulation and improved Inheritance
2 parents b9fe426 + 39304fe commit ba14199

File tree

1 file changed

+31
-10
lines changed

1 file changed

+31
-10
lines changed

python_sandbox_finished/classes.py

Lines changed: 31 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,33 +2,41 @@
22

33
# Create class
44
class User:
5+
56
# Constructor
67
def __init__(self, name, email, age):
78
self.name = name
89
self.email = email
910
self.age = age
11+
12+
# Adding Encapsulation of variables... Encapsulation is the concept of making the variables non-accessible or accessible upto some extent from the child classes
13+
self._private = 1000 # Encapsulated variables are declares with '_' in the constructor.
1014

1115
def greeting(self):
12-
return f'My name is {self.name} and I am {self.age}'
16+
return f'My name is {self.name} and I am {self.age}'
1317

1418
def has_birthday(self):
15-
self.age += 1
16-
19+
self.age += 1
20+
21+
#function for encap variable
22+
def print_encap(self):
23+
print(self._private)
1724

1825
# Extend class
1926
class Customer(User):
2027
# Constructor
2128
def __init__(self, name, email, age):
22-
self.name = name
23-
self.email = email
24-
self.age = age
25-
self.balance = 0
29+
User.__init__(self, name, email, age) #Called proper parent class constructor to make this as proper child inehriting all methods.
30+
self.name = name
31+
self.email = email
32+
self.age = age
33+
self.balance = 0
2634

2735
def set_balance(self, balance):
28-
self.balance = balance
36+
self.balance = balance
2937

3038
def greeting(self):
31-
return f'My name is {self.name} and I am {self.age} and my balance is {self.balance}'
39+
return f'My name is {self.name} and I am {self.age} and my balance is {self.balance}'
3240

3341
# Init user object
3442
brad = User('Brad Traversy', 'brad@gmail.com', 37)
@@ -39,4 +47,17 @@ def greeting(self):
3947
print(janet.greeting())
4048

4149
brad.has_birthday()
42-
print(brad.greeting())
50+
print(brad.greeting())
51+
52+
#Encapsulation -->
53+
brad.print_encap()
54+
brad._private = 800 #Changing for brad
55+
brad.print_encap()
56+
57+
# Method inherited from parent
58+
janet.print_encap() #Changing the variable for brad doesn't affect janets variable --> Encapsulation
59+
janet._private = 600
60+
janet.print_encap()
61+
62+
#Similary changing janet's doesn't affect brad's variable.
63+
brad.print_encap()

0 commit comments

Comments
 (0)