python @property

在python源码中property这个类的一个例子:

class C(object):
            @property
            def x(self):
                "I am the 'x' property."
                return self._x
            @x.setter
            def x(self, value):
                self._x = value
            @x.deleter
            def x(self):
                del self._x

这个类是一个装饰器,这个装饰器的作用是让我能像变量一样访问和设置类的方法

访问这个实例变量:

test = C()
test.x
Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\site-packages\IPython\core\interactiveshell.py", line 3417, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-42-8d783f11fee3>", line 2, in <module>
    test.x
  File "<ipython-input-40-6bcb8eb63906>", line 5, in x
    return self._x
AttributeError: 'C' object has no attribute '_x'

因为还没有设置这个变量

现在设置一下:

test.x = 100
test.x
Out[44]: 100

注意:

类的方法加上装饰器@property之后,调用这个实例方法 是 实例对象.方法  等于  没有加上装饰器@property时的 实例对象.方法()

类的方法加上装饰器@方法名.setter之后,调用这个实例方法 是 实例对象.方法 = 参数 等于  没有加上装饰器@方法名.setter 时的 实例对象.方法(参数)

同时如果这个方法使用过之后或者这个方法返回 类的变量 或者 返回类变量 ,会成为 实例 的属性(hasattr(test,'x')) -->True

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值