DEV Community

Cover image for Getter and Setter - Python
Aitor
Aitor

Posted on

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

(Thank you Danben for your Answer)

How do i write it in Python?

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

Enter fullscreen mode Exit fullscreen mode

Top comments (0)