欢迎使用Markdown编辑器写博客
@property 装饰器可以将类函数包装成实例的属性,通过访问实例属性来操作函数。
class Test(object):
def init(self):
self._voltage = 110
def get_x(self):
"""Get the current voltage."""
return self._voltage
def set_x(self, value):
self._voltage = value
def del_x(self):
del self._voltage
x = property(get_x,set_x,del_x)
或者:
class Test(object):
def init(self):
self._voltage = 110
@property
def x(self):
"""Get the current voltage."""
return self._voltage
@x.setter
def x(self, value):
self._voltage = value
@x.deleter
def x(self):
del self._voltage
t = Test()
print t.x # 110
t.x = 220
print t.x # 220
del t.x
print t.x # 报错