国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

python - 程序運行會出現錯誤

瀏覽:126日期:2022-06-27 17:51:54

問題描述

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........ 無盡的迭代,

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

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 黄浦区| 平度市| 尼勒克县| 元谋县| 五台县| 临夏县| 曲阜市| 天长市| 共和县| 汤阴县| 右玉县| 黎平县| 盈江县| 大邑县| 德州市| 克东县| 闽清县| 新密市| 通辽市| 托里县| 肇源县| 九江市| 墨玉县| 维西| 海南省| 梁平县| 秦皇岛市| 新巴尔虎右旗| 工布江达县| 阿尔山市| 比如县| 永靖县| 桦甸市| 柘荣县| 和龙市| 德江县| 西乌珠穆沁旗| 迁安市| 玉溪市| 萍乡市| 山东省|