Sometimes, we want to use getters and setters with Python.
In this article, we’ll look at how to use getters and setters with Python.
How to use getters and setters with Python?
To use getters and setters with Python, we can use the property
, setter
and deleter
decorators.
deleter
is called when the del
keyword is used to remove an attribute from an object.
For instance, we write:
class C(object):
def __init__(self):
self._x = None
@property
def x(self):
print("getter of x called")
return self._x
@x.setter
def x(self, value):
print("setter of x called")
self._x = value
@x.deleter
def x(self):
print("deleter of x called")
del self._x
c = C()
c.x = 'foo'
foo = c.x
del c.x
We have the C
class with the x
getter which has the property
decorator applied to it and returns self._x
.
The x
setter has the x.setter
called on it and sets self._x
to value
.
value
is the value that we assign to x
.
The x
deleter has the x.deleter
used on it and uses the del
operator to remove the self._x
property.
Then we instantiate C
and assigns it to c
.
And then we set c.x
to 'foo'
, assigns c.x
fo foo
, and use del
to remove the c.x
attribute.
Therefore, we see:
setter of x called
getter of x called
deleter of x called
printed.
Conclusion
To use getters and setters with Python, we can use the property
, setter
and deleter
decorators.
deleter
is called when the del
keyword is used to remove an attribute from an object.