python - 程序運(yùn)行會(huì)出現(xiàn)錯(cuò)誤
問題描述
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
在運(yùn)行這個(gè)程序時(shí),只有當(dāng)score是私有變量的時(shí)候才能正常運(yùn)行,是property的某些特性嗎,還是什么?如果只設(shè)置為self.score = score,就會(huì)出現(xiàn)‘maximum recursion depth exceeded while calling a Python object’的錯(cuò)誤,求大神解答
問題解答
回答1:會(huì)產(chǎn)生這個(gè)困惑的原因是對(duì)python的getter裝飾器和setter裝飾器不夠熟悉
當(dāng)你聲明了對(duì)score屬性的setter裝飾器之后, 實(shí)際上對(duì)這個(gè)score進(jìn)行賦值就是調(diào)用這個(gè)setter裝飾器綁定的方法
所以你的setter要訪問的成員變量不能和setter方法同名, 不然就相當(dāng)于一個(gè)無盡的迭代:
self.score(self.score(self.score(self.score(self.score........ 無盡的迭代,
當(dāng)然會(huì)報(bào)超過最大迭代深度的錯(cuò)誤了
相關(guān)文章:
1. python - Django有哪些成功項(xiàng)目?2. 實(shí)現(xiàn)bing搜索工具urlAPI提交3. MySQL主鍵沖突時(shí)的更新操作和替換操作在功能上有什么差別(如圖)4. Python從URL中提取域名5. 關(guān)于mysql聯(lián)合查詢一對(duì)多的顯示結(jié)果問題6. 數(shù)據(jù)庫(kù) - Mysql的存儲(chǔ)過程真的是個(gè)坑!求助下面的存儲(chǔ)過程哪里錯(cuò)啦,實(shí)在是找不到哪里的問題了。7. node.js - 微信小程序websocket連接問題8. 直接打字符不可以嗎?>和>有區(qū)別嗎9. node.js - windows10下的npm全局路徑的復(fù)原或者將npm徹底刪除?10. Python中使用超長(zhǎng)的List導(dǎo)致內(nèi)存占用過大
