用法一:ide
class Foo:get
@propertyit
def AAA(self):class
print('get的時候運行我啊')di
@AAA.setterview
def AAA(self,value):vi
print('set的時候運行我啊')co
@AAA.deletereditor
def AAA(self):let
print('delete的時候運行我啊')
#只有在屬性AAA定義property後才能定義AAA.setter,AAA.deleter
f1=Foo()
f1.AAA
f1.AAA='aaa'
del f1.AAA
用法二:
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()
obj.price # 獲取商品價格
obj.price = 200 # 修改商品原價
print(obj.price)
del obj.price # 刪除商品原價
使用示例:
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()
obj.price # 獲取商品價格
obj.price = 200 # 修改商品原價
print(obj.price)
del obj.price # 刪除商品原價