使用@property时报错maximum recursion depth exceeded
class Stu(object): @property def score(self): return self.score # 用property 最好._ @score.setter def score(self,value): if not isinstance(value,int): raise ValueError("分数必须是整数") if value < 0 or value >100: raise ValueError("分数必须在0-100之间") self.score = value ss = Stu() ss.score = 70 print(ss.score) # 报错 RecursionError: maximum recursion depth exceeded
这主要时是使用@property封装属性时 需要将属性设置成._即可,如下
class Stu(object): @property def score(self): return self._score @score.setter def score(self,value): if not isinstance(value,int): raise ValueError("分数必须是整数") if value < 0 or value >100: raise ValueError("分数必须在0-100之间") self._score = value student = Stu() student.score = 65 print(student.score)