python中有装饰器的概念,@property是装饰器的一种。
以下面的例子进行说明:
私有属性以双下划线__开头:外部不可通过instance.property来访问或者更改。如果一定要,可以通过setName(),getName()等方法实现,可是这样不简洁。
但是,使用@property
可以优雅的对私有属性 __amt 进行访问。
acc.amount
使用@amount.setter
可以优雅的对私有属性 __amt 进行更改。还能扩展功能,比如增加过滤条件。
acc.amount = 20
#!/usr/bin/env python3
class Account(object):
"""账号类,
amount 是美元金额.
"""
def __init__(self, rate):
self.__amt = 0
self.rate = rate
@property
def amount(self):
"""账号余额(美元)"""
return self.__amt
@property
def cny(self):
"""账号余额(人民币)"""
return self.__amt * self.rate
@amount.setter
def amount(self, value):
if value < 0:
print("Sorry, no negative amount in the account.")
return
self.__amt = value
if __name__ == '__main__':
acc = Account(rate=6.6) # 基于编写时的汇率
acc.amount = 20
print("Dollar amount:", acc.amount)
print("In CNY:", acc.cny)
acc.amount = -100
print("Dollar amount:", acc.amount)