Python之——property

作者: cynthia猫 | 来源:发表于2018-08-08 13:23 被阅读21次

@property成为属性函数,可以对属性赋值时做必要的检查,并保证代码的清晰短小,主要有2个作用

  • 将方法转换为只读
  • 重新实现一个属性的设置和读取方法,可做边界判定
class Money(object):
    def __init__(self):
        self.__money = 0

    @property
    def num(self):
        return self.__money

    @num.setter
    def num(self, value):
        if isinstance(value, int):
            self.__money = value
        else:
            print("error:不是整型数字")

t = Money()
t.num = 100
print (t.num)

注意:@property放在哪个函数前面,这个函数就是getter,而且用的时候,就是这个函数名。如上例,就是num。
那么这个函数名.setter放在哪个函数前面,这个函数就是setter。如上例,就是@num.setter
所以你不要看我给Money类定义的时候是用了__money,为啥后面赋值和调用的时候用的都是num呢,这和setter、getter的函数设置有关。

相关文章

  • python @property

    参考 Python进阶之“属性(property)”详解 - Python - 伯乐在线

  • Python之——property

    @property成为属性函数,可以对属性赋值时做必要的检查,并保证代码的清晰短小,主要有2个作用 将方法转换为只...

  • Python进阶——面向对象

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

  • 2018-02-05

    python @property装饰器

  • Python中property中的小坑

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

  • property, getter, setter and del

    http://www.runoob.com/python/python-func-property.htmlhtt...

  • 重识iOS之Property

    重识iOS之Property 重识iOS之Property

  • Python property

    Question 我们一般对属性的的操作主要有2个,访问和修改。看个例子。 我们叫这种使用属性的方式叫点模式(我自...

  • python @property

    1.描述符 我们首先要搞懂描述符(Descriptor)是什么. 1.1 描述符定义 只要类中有__get__()...

  • Python @property

    以下内容来自万能的互联网... 首先教材上的@property 可以将一个方法的调用变成“属性调用”,主要用于帮助...

网友评论

    本文标题:Python之——property

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