美文网首页
Python中property中的小坑

Python中property中的小坑

作者: Rokkia | 来源:发表于2016-10-10 14:27 被阅读148次

    刚刚了解了python中的@property的使用,property本质是python中的一个内置修饰器。使用大概如下

    class Student(object):
         def __init__(self):
             pass
         @property
         def score(self):
             return self._score
         @score.setter
         def score(self,value):
             if value < 0 or value > 100:
                 return 'please input right value!' 
             self._score = value
    #创建
    s1 = Student()
    #执行了setter方法
    s1.score = 100
    #执行了getter方法
    s1.score
    100
    

    但是我开始写的时候是这样写的

    class Student(object):
         def __init__(self):
             pass
         @property
         def score(self):
             #用score是不行的 需要使用_score
             return self.score
         @score.setter
         def score(self,value):
             if value < 0 or value > 100:
                 return 'please input right value!' 
             self.score = value
    
    s1 = Student()
    #当我想要赋值,直接给我报错,百度翻译一查才知道  
    s1.score = 100
    RuntimeError: maximum recursion depth exceeded
    #百度翻译 "最大递归深度超过"
    

    使用score是不行的 需要使用_score,看看报错理由也可以理解,如果你使用score,使用self.score赋值时,相当于又有执行了setter方法,就会一直递归,
    然后崩溃,所以可是使用_score 或者__score来使用。

    本文只是对自己平时学习的总结,如有不对的地方,还望各位指出,一起交流学习

    相关文章

      网友评论

          本文标题:Python中property中的小坑

          本文链接:https://www.haomeiwen.com/subject/rhzmyttx.html