Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

infinite recursion in python3.3 setter

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 ?

like image 868
asit_dhal Avatar asked May 11 '26 09:05

asit_dhal


1 Answers

@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
like image 84
Kevin Avatar answered May 12 '26 22:05

Kevin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!