美文网首页
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中的小坑

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

  • Python中 @property

    https://www.cnblogs.com/Lambda721/p/6132206.html

  • Python进阶——面向对象

    1. Python中的@property   @property是python自带的装饰器,装饰器(decorat...

  • Python中的property

    Python中的property是用于实现属性可管理性的bulit-in数据类型(从表现上来看,property是...

  • Python中的property

    使用property升级getter和setter 如果一直使用getter和setter方法,会比较繁杂。想要快...

  • Python中的property属性

    Python中有个很赞的概念,叫做property,它使得面向对象的编程更加简单。在详细解释和深入了解Python...

  • python中@property的使用

    今天遇到一个问题: 报错了,经过改正后的代码如下: 想不到吧,一个小小的下划线竟然是罪魁祸首。不过还是不能理解,为...

  • Python中的lazy property

    我们都知道,在Python的类中,dict保存了一个对象所有的属性,如下面的例子,我们建立了一个Circle的对象...

  • python使用中的小坑

    anaconda 安装包失败使用下面命令更新pip再安装即可 python -m pip install --up...

  • python中的装饰器

    python中的装饰器 1. @property ['prɑpɚti] @property装饰器就是负责把一个方法...

网友评论

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

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