python - 程序運(yùn)行會出現(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,就會出現(xiàn)‘maximum recursion depth exceeded while calling a Python object’的錯(cuò)誤,求大神解答
問題解答
回答1:會產(chǎn)生這個(gè)困惑的原因是對python的getter裝飾器和setter裝飾器不夠熟悉
當(dāng)你聲明了對score屬性的setter裝飾器之后, 實(shí)際上對這個(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)然會報(bào)超過最大迭代深度的錯(cuò)誤了
相關(guān)文章:
1. 我在centos容器里安裝docker,也就是在容器里安裝容器,報(bào)錯(cuò)了?2. docker不顯示端口映射呢?3. docker-machine添加一個(gè)已有的docker主機(jī)問題4. golang - 用IDE看docker源碼時(shí)的小問題5. docker-compose中volumes的問題6. 在windows下安裝docker Toolbox 啟動(dòng)Docker Quickstart Terminal 失敗!7. docker內(nèi)創(chuàng)建jenkins訪問另一個(gè)容器下的服務(wù)器問題8. javascript - 最近用echarts做統(tǒng)計(jì)圖時(shí)遇到兩個(gè)問題!!9. docker容器呢SSH為什么連不通呢?10. mac里的docker如何命令行開啟呢?

網(wǎng)公網(wǎng)安備