python基础-面向对象(二十五)面向对象进阶(十三)系统内置的property
1.官方的文档。
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 # (copied from class doc)
2.property的查改删可以有两种形式,一种是
class Goods: def __init__(self): self.original_price = 100 self.discount = 0.8 @property def price(self): new_price = self.original_price * self.discount return new_price @price.setter def price(self, value): self.original_price = value @price.deleter def price(self): del self.original_price obj = Goods() print(obj.price) obj.price = 200 print(obj.price) del obj.price print(obj.price)

3.另一种格式
class Goods: def __init__(self): self.original_price = 100 self.discount = 0.8 def get_price(self): new_price = self.original_price * self.discount return new_price def settt_price(self, value): self.original_price = value def ssssss_price(self): print('from ssssss_price') price = property(get_price, settt_price, ssssss_price) # 不管方法名字,反正调用是按查,改,删的顺序 goods = Goods() print(goods.price) goods.price = 200 print(goods.price) del goods.price


浙公网安备 33010602011771号