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. python - scrapy 如何組合2個不同頁面的數據,一并存儲2. mysql優化 - mysql 一張表如果不能確保字段列長度一致,是不是就不需要用到char。3. node.js - mysql如何通過knex查詢今天和七天內的匯總數據4. javascript - 用jsonp抓取qq音樂總是說回調函數沒有定義5. javascript - 新浪微博網頁版的字數限制是怎么做的6. sublime可以用其他編譯器替換嗎?7. python2.7 - python 函數或者類 代碼的執行順序8. 使用python中的pandas求每個值占該列的比例9. python - 多態調用方法時卻顯示bound method...10. mysql 怎么做到update只更新一行數據?
