装饰器(Decorators)用来给一些对象动态的添加一些新的行为
这里我们先创建一个简单的示例,将在函数执行前后打印一些语句
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before call")
result = func(*args, **kwargs)
print("After call")
return result
return wrapper
@my_decorator
def add(a, b):
print("a={},b={}".format(a, b))
return a+b
print(add(1, 4))
当我们需要精确的调整控制属性访问权限,可以使用 @property 装饰器,@property 装饰器就是负责把一个方法变成属性调用的
#!/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)