2
votes

Can somebody tell me why there is a recursion in the following code ?

class A:

    def __init__(self):
        self.a = 0

    @property
    def a(self):
        print ("called a getter")
        return self.a

    @a.setter
    def a(self, value):
        print ("called a setter")
        self.a = value


class B(A):

    def check(self):
        a = 10


if __name__ == "__main__":
    bb = B()
    bb.check()

I have to call a base class setter from child class. I am not allowed to access the member directly. Can somebody tell me how to do other way ?

1

1 Answers

10
votes
@a.setter
def a(self, value):
    print ("called a setter")
    self.a = value

When self.a = value executes, it calls your method a(self, value) again, which executes self.a = value again, which calls a(self, value)... etc.

The conventional solution is to have different names for the property and the underlying attribute. Ex. you can add an underscore to the front.

class A:

    def __init__(self):
        self._a = 0

    @property
    def a(self):
        print ("called a getter")
        return self._a

    @a.setter
    def a(self, value):
        print ("called a setter")
        self._a = value