What’s the pythonic way to use getters and setters?

Try this: Python Property

The sample code is:

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

    def x(self):
        """I'm the 'x' property."""
        print("getter of x called")
        return self._x

    def x(self, value):
        print("setter of x called")
        self._x = value

    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

Leave a Comment