11
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.
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
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
Mostly for two reasons, encapsulation and to maintain a consistent interface in case internal details change
The syntax for doing that is as follows
>>> class MyClass:
>>> def __init__(self, A, B=None):
>>> self._A = A
>>> self._B = B
>>> @property
>>> def A(self):
>>> return self._A
>>> @A.setter
>>> def A(self, A):
>>> self._A = A
>>>
>>> @property
>>> def B(self):
>>> return self._B
>>>
>>> @B.setter
>>> def B(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
11