property() 函数作用于新式类,返回属性值。
class C(object): def __init__(self): self._x = None def getx(self): print('get') return self._x def setx(self, value): print('set') self._x = value def delx(self): print('del') del self._x x = property(getx, setx, delx, "I'm the 'x' property.") # c = C() # c.x = 12 # print(c.x) # del c.x
@property 装饰器用的最多。把一个方法变成属性调用,那么我们在对实例属性操作的时候,就知道该属性很可能不是直接暴露的,而是通过getter和setter方法来实现的。
# @property 装饰器负责把一个方法变成属性调用 class Student(object): # 把一个getter方法变成属性,只需加上 @property @property def score(self): return self._score # 把一个setter方法变成属性,@fun.setter @score.setter def score(self, value): if not isinstance(value, int): raise ValueError('score must be an interger!') if value < 0 or value > 100: raise ValueError('score must between 0~100') self._score = value s = Student() s.score = 60 print(s.score)
class Parrot(object): def __init__(self): self._voltage = 100000 @property def voltage(self): """Get the current voltage.""" return self._voltage # setter,deleter,这些额外函数名和property相同 @voltage.setter def voltage(self, value): self._voltage = value @voltage.deleter def voltage(self): del self._voltage
参考:
https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00143186781871161bc8d6497004764b398401a401d4cce000
http://www.runoob.com/python/python-func-property.html