Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

python - 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
@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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...