Search code examples
pythongetter-setter

How to use get/set methods?


Please point where a bug in my code.

class Foo:
    def get(self):
        return self.a

    def set(self, a):
        self.a = a

Foo.set(10)
Foo.get()

TypeError: set() takes exactly 2 positional arguments (1 given)

How to use __get__()/__set__()?


Solution

  • They are instance methods. You have to create an instance of Foo first:

    f = Foo()
    f.set(10)
    f.get()    # Returns 10