python属性和property_python@属性,pythonproperty

在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 "", line 2, in

test.x

File "", line 5, in x

return self._x

AttributeError: 'C' object has no attribute '_x'

因为还没有设置这个变量

现在

设置

一下:

test.x = 100

test.x

Out[44]: 100

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值