-
Notifications
You must be signed in to change notification settings - Fork 0
/
getters_setters.py
126 lines (86 loc) · 2.66 KB
/
getters_setters.py
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
class SampleClass:
def __init__(self, a):
# private variable or property in Python
self.__a = a
self.stam = a // 3
# getter method to get the properties using an object
def get_a(self):
return f"A: {self.__a}"
# setter method to change the value 'a' using an object
def set_a(self, a):
self.__a = a
# creating an object
obj = SampleClass(10)
# getting the value of 'a' using get_a() method
print(obj.get_a())
# setting a new value to the 'a' using set_a() method
obj.set_a(45)
print(obj.get_a())
print(obj.stam)
obj.stam = 45
# =================================================
class PythonSimpleWay:
def __init__(self, a):
self.a = a
# Create an object for the 'PythonSimpleWay' class
obj = PythonSimpleWay(100)
print(obj.a)
# =================================================
class SampleClass1:
def __init__(self, a):
# calling the set_a() method to set the value 'a' by checking certain conditions
self.set_a(a)
# getter method to get the properties using an object
def get_a(self):
return self.__a
# setter method to change the value 'a' using an object
def set_a(self, a):
# condition to check whether 'a' is suitable or not
if a > 0 and a % 2 == 0:
self.__a = a
else:
self.__a = 2
# create an object for the class 'SampleClass1'
obj = SampleClass1(16)
print(obj.get_a())
# =================================================
class Property:
def __init__(self, var):
# initializing the attribute
self.a = var
@property
def a(self):
return self.__a
# the attribute name and the method name must be same
# which is used to set the value for the attribute
@a.setter
def a(self, var):
if var > 0 and var % 2 == 0:
self.__a = var
else:
self.__a = 2
# creating an object for the class 'Property'
obj = Property(23)
print(obj.a)
obj.a = 345
print(obj.a)
# =================================================
class FinalClass:
def __init__(self, var):
# calling the set_a() method to set the value 'a' by checking certain conditions
self.__set_a(var)
# getter method to get the properties using an object
def __get_a(self):
return self.__a
# setter method to change the value 'a' using an object
def __set_a(self, var):
if var > 0 and var % 2 == 0:
self.__a = var
else:
self.__a = 2
a = property(__get_a, __set_a)
# creating an object for the 'FinalClass' class
obj = FinalClass(12)
print('FinalClass:', obj.a)
obj.a = 345
print('FinalClass:', obj.a)