This repository was archived by the owner on Aug 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathoop-access-modifiers.py
More file actions
58 lines (42 loc) · 1.38 KB
/
oop-access-modifiers.py
File metadata and controls
58 lines (42 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class MyClass:
name = "PUBLIC"
_family = "PROTECTED"
__middle = "PRIVATE"
def get_private_variable(self):
return self.__middle
@property
def family(self):
return self._family
@family.setter
def family(self, value):
self._family = value
# ------------------------------------------------------------
# Public member
print(MyClass.name)
# ------------------------------------------------------------
# Protected member - Property
print(MyClass._family) # Accessible - but do not use it like this
cls = MyClass()
print(cls.family)
cls.family += "-Changed"
print(cls.family)
print(cls._family) # Accessible - but do not use it like this
# ------------------------------------------------------------
# Private member
# print(MyClass.__middle) # AttributeError: type object 'MyClass' has no attribute '__middle'
print(MyClass().get_private_variable())
# ------------------------------------------------------------
class DerivedClass(MyClass):
name="PUBLIC2"
_family="PROTECTED2"
__middle = "New Private Middle Name"
cls = MyClass()
dcls = DerivedClass()
print(cls.name," --- ", dcls.name)
print(cls._family," --- ", dcls._family)
print(cls.get_private_variable()," --- ", dcls.get_private_variable()) # __middle in new class is not shadowed the original one
"""
PUBLIC --- PUBLIC2
PROTECTED --- PROTECTED2
PRIVATE --- PRIVATE
"""