使用屬性裝飾器進行讀寫屬性
如果要使用 @property
實現設定和獲取的自定義行為,請使用以下模式:
class Cash(object):
def __init__(self, value):
self.value = value
@property
def formatted(self):
return '${:.2f}'.format(self.value)
@formatted.setter
def formatted(self, new):
self.value = float(new[1:])
要使用它:
>>> wallet = Cash(2.50)
>>> print(wallet.formatted)
$2.50
>>> print(wallet.value)
2.5
>>> wallet.formatted = '$123.45'
>>> print(wallet.formatted)
$123.45
>>> print(wallet.value)
123.45