美文网首页Python
2019-05-28 使用@property

2019-05-28 使用@property

作者: 沙滩印 | 来源:发表于2019-05-28 14:13 被阅读0次

Python内置的@property装饰器就是负责把一个方法变成属性调用的:

class Student(object):

    @property
    def score(self):
        return self._score

    @score.setter
    def score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an integer!')
        if value < 0 or value > 100:
            raise ValueError('score must between 0 ~ 100!')
        self._score = value

@property的实现比较复杂,我们先考察如何使用。把一个getter方法变成属性,只需要加上@property就可以了,此时,@property本身又创建了另一个装饰器@score.setter,负责把一个setter方法变成属性赋值,于是,我们就拥有一个可控的属性操作:

>>> s = Student()
>>> s.score = 60 # OK,实际转化为s.set_score(60)
>>> s.score # OK,实际转化为s.get_score()
60
>>> s.score = 9999
Traceback (most recent call last):
  ...
ValueError: score must between 0 ~ 100!

注意到这个神奇的@property,我们在对实例属性操作的时候,就知道该属性很可能不是直接暴露的,而是通过getter和setter方法来实现的。

还可以定义只读属性,只定义getter方法,不定义setter方法就是一个只读属性:

class Student(object):

    @property
    def birth(self):
        return self._birth

    @birth.setter
    def birth(self, value):
        self._birth = value

    @property
    def age(self):
        return 2015 - self._birth

上面的birth是可读写属性,而age就是一个只读属性,因为age可以根据birth和当前时间计算出来。

小结

@property广泛应用在类的定义中,可以让调用者写出简短的代码,同时保证对参数进行必要的检查,这样,程序运行时就减少了出错的可能性。
如果你的属性名称跟方法名称一致,但是属性又不是私有的,那么会存在递归调用get的那个方法,导致报错。

相关文章

  • 2019-05-28 使用@property

    Python内置的@property装饰器就是负责把一个方法变成属性调用的: @property的实现比较复杂,我...

  • Category添加成员变量

    类中使用@property @property (nonatomic,strong) NSString * nam...

  • 使用property

    有没有既能检查参数,又可以用类似属性这样简单的方式来访问类的变量呢?Python内置的@property装饰器就是...

  • @property使用

    根据廖雪峰教程自己学习。 @property的使用简洁体现在:s1=Studnet() 赋值的时候直接用.属性名...

  • 使用 @property

    在绑定属性时,如果我们直接把属性暴露出去,虽然写起来很简单,但是,没办法检查参数,导致可以把成绩随便改: 这显然不...

  • 使用@property

    使用@property:(首先,这个一般是放在类里边,其次这个放在类内函数之上) 既能检查参数(就是通过get()...

  • iOS开发小知识笔记

    1 @property @property 是 readwrite,assign,atomic 在使用 @prop...

  • iOS开发小知识笔记 (1)property

    1 @property @property 是 readwrite,assign,atomic 在使用 @pro...

  • iOS面试之@property

    原文链接 @property介绍 相信做过iOS开发的同学都使用过@property,@property翻译过来是...

  • iOS开发中@property引伸的各种问题

    @property介绍 相信做过iOS开发的同学都使用过@property,@property翻译过来是属性。在定...

网友评论

    本文标题:2019-05-28 使用@property

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