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. node.js - gulp文件監(jiān)聽的問題2. node.js - node 客戶端socket一直報(bào)錯(cuò)Error: read ECONNRESET,用php的socket沒問題哈。。3. python - 模擬滑動(dòng)驗(yàn)證碼,有源碼,求解4. npm鏡像站全新上線5. mySql排序,序號(hào)6. tp6表單令牌7. 老哥們求助啊8. javascript - vue-router怎么不能實(shí)現(xiàn)跳轉(zhuǎn)呢9. html5 - angularjs中外部模版加載無法使用10. css3 - 請(qǐng)問一下在移動(dòng)端CSS布局布局中通常需要用到哪些元素,屬性?
