This website collects cookies to deliver better user experience
Getter and Setter - Python
Getter and Setter - Python
As the title says, I am presenting, Getters and Setters for
First, let's review some OOP concepts, then we will see what are those (If you thought of crocs, consider leaving a unicorn) getters and setters.
OOP Concepts
Method = A function from a class
Property = A variable from a class
A property starting with "_" = Private property (i.e it can only be accessed from within the class)
Apopathodiaphulatophobie = Exaggerated fear of constipation
Getter and Setter
A getter is a method that is used to obtain a property of a class
A setter is a method that is used to set the property of a class
Why do these two exists?
Mostly for two reasons, encapsulation and to maintain a consistent interface in case internal details change
>>>classMyClass:>>>def__init__(self, A, B=None):>>> self._A = A
>>> self._B = B
>>> @property>>>defA(self):>>>return self._A
>>> @A.setter
>>>defA(self, A):>>> self._A = A
>>>>>> @property>>>defB(self):>>>return self._B
>>>>>> @B.setter
>>>defB(self, B):>>> self._B = B
>>>>>> instance = MyClass("This is A")>>>print(instance.A)This is A
>>> instance.A ="A Changed">>>print(instance.A)A Changed
>>>print(instance.B)None>>> instance.B ="This is B">>>print(instance.B)This is B