DEV Community

Cover image for Getter and Setter - Python
Aitor
Aitor

Posted on

3 2

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay