property属性的用法
property装饰器装饰的方法将成为特性, 特性是类的特殊属性, 会覆盖同名的实例属性, 也可偶一通过类名重写.property默认是getter方法, 必须有返回值, 设定特性需要定义同名方法,并用特姓名.setter装饰.
DEMO
商品的 进货价是保密的,用私有属性设定, 售价可能需要改动,但需要有限制条件,因此使用特性定义.我们不希望外部直接访问或修改价格的内部定义, 因此使用受保护的实例属性_price在内部存储未公布的价格.
class Goods():
__profit_margin = 0.4
def __init__(self, prochase_price):
self.__purchase_price = prochase_price
self._price = self.__purchase_price * (1 + self.__profit_margin)
@property
def price(self):
return self._price
@price.setter
def price(self, price):
self._price = price * 1.0
assert self.__purchase_price < self._price, "注意, 低于成本价了!"
if __name__ == '__main__':
g = Goods(100)
print(g.price)
g.price = 120
print(g.price)
或者
class Goods():
__profit_margin = 0.4
def __init__(self, prochase_price):
self.__purchase_price = prochase_price
self._price = self.__purchase_price * (1 + self.__profit_margin)
def get_price(self):
return self._price
def set_price(self, price):
self._price = price * 1.0
assert self.__purchase_price < self._price, "注意, 低于成本价了!"
price = property(get_price, set_price)
if __name__ == '__main__':
g = Goods(100)
print(g.price)
g.price = 120
print(g.price)