在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