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
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:
Of course, an error of exceeding the maximum iteration depth will be reported