python - 程序運行會出現錯誤
問題描述
class Person(object): def __init__(self,name):self.name = nameclass Teacher(Person): def __init__(self,score):self.__score = scoreclass 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 = 95print s1
在運行這個程序時,只有當score是私有變量的時候才能正常運行,是property的某些特性嗎,還是什么?如果只設置為self.score = score,就會出現‘maximum recursion depth exceeded while calling a Python object’的錯誤,求大神解答
問題解答
回答1:會產生這個困惑的原因是對python的getter裝飾器和setter裝飾器不夠熟悉
當你聲明了對score屬性的setter裝飾器之后, 實際上對這個score進行賦值就是調用這個setter裝飾器綁定的方法
所以你的setter要訪問的成員變量不能和setter方法同名, 不然就相當于一個無盡的迭代:
self.score(self.score(self.score(self.score(self.score........ 無盡的迭代,
當然會報超過最大迭代深度的錯誤了
相關文章:
1. css - 新手做響應式布局, 斷點過后右側出現空白,求幫助,謝謝。2. javascript - 關于<a>元素與<input>元素的JS事件運行問題3. css3 - 純css實現點擊特效4. mysql - 查詢字段做了索引為什么不起效,還有查詢一個月的時候數據都是全部出來的,如果分拆3次的話就沒問題,為什么呢。5. mysql - 記得以前在哪里看過一個估算時間的網站6. 大家好,我想請問一下怎么做搜索欄能夠搜索到自己網站的內容。7. ID主鍵不是自增的嗎 為什么還要加null8. MySQL中的enum類型有什么優點?9. python - 啟動Eric6時報錯:’qscintilla_zh_CN’ could not be loaded10. javascript - vue 怎么渲染自定義組件
