在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