python - 程式運行會出現錯誤
过去多啦不再A梦
过去多啦不再A梦 2017-06-22 11:52:35
0
1
720
class Person(object):
    def __init__(self,name):
        self.name = name
class Teacher(Person):
    def __init__(self,score):
        self.__score = score
class 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 = 95
print s1

在執行這個程式時,只有當score是私有變數的時候才能正常運作,是property的某些特性嗎,還是什麼?如果只設定為self.score = score,就會出現‘maximum recursion depth exceeded while calling a Python object’的錯誤,求大神解答

过去多啦不再A梦
过去多啦不再A梦

全部回覆(1)
洪涛

會產生這個困惑的原因是對python的getter裝飾器和setter裝飾器不夠熟悉

當你聲明了對score屬性的setter裝飾器之後, 實際上對這個score進行賦值就是調用這個setter裝飾器綁定的方法

所以你的setter要存取的成員變數不能和setter方法同名, 不然就相當於一個無盡的迭代:

self.score(self.score(self.score(self.score(self.score........ 无尽的迭代,

當然會報超過最大迭代深度的錯誤了

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!