python - error occurs when running the program
过去多啦不再A梦
过去多啦不再A梦 2017-06-22 11:52:35
0
1
721
class Person(object):
    def __init__(self,name):
        self.name = name
class Teacher(Person):
    def __init__(self,score):
        self.__score = score
class Student(Teacher,Person):
    def __init__(self,name,score):
        Person.__init__(self,name)
        super(Student,self).__init__(score)
    @property
    def score(self):
        return self.__score
    @score.setter
    def score(self,score):
        if score<0 or score >100:
            raise ValueError('invalid score')
        self.__score = score
    def __str__(self):
        return 'Student:%s,%d' %(self.name,self.score)

s1 = Student('Jack',89)
s1.score = 95
print s1

When running this program, it can only run normally when score is a private variable. Is it some feature of the property, or what? If you only set it to self.score = score, the error 'maximum recursion depth exceeded while calling a Python object' will appear. Please give me an answer

过去多啦不再A梦
过去多啦不再A梦

reply all(1)
洪涛

The reason for this confusion is that you are not familiar enough with python’s getter decorator and setter decorator

After you declare the setter decorator for the score attribute, actually assigning the score is to call the method bound by the setter decorator

So the member variable your setter wants to access cannot have the same name as the setter method, otherwise it will be equivalent to an endless iteration:

self.score(self.score(self.score(self.score(self.score........ 无尽的迭代,

Of course, an error of exceeding the maximum iteration depth will be reported

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!