python setter getter deleter 1

python setter getter deleter

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        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'  # setter called
foo = c.x    # getter called
del c.x      # deleter called

Here is what the above code is Doing:
1. The @property decorator turns the x() method into a “getter” for retrieving the value of x.
2. The @x.setter decorator turns the x() method into a “setter” for setting the value of x.
3. The @x.deleter decorator turns the x() method into a “deleter” for deleting the value of x.

Similar Posts