@Scrazy
2016-02-15T08:34:29.000000Z
字数 1407
阅读 943
python学习笔记
基于函数的decorator
def decorator(F):def new_F(a, b):print('input:', a, b)return F(a, b)return new_F@decoratordef square_sum(a, b):return a**2 + b** 2@decoratordef square_diff(a, b):return a**2 - b** 2print(square_sum(3, 4))print(square_diff(3, 4))
运行
/usr/bin/python3.4input: 3 425input: 3 4-7
当然也可以两个装饰器一起使用
函数的执行顺序由@decorator的顺序决定
def decorator(F):def new_F(a, b):print('input:', a, b)return F(a, b)return new_Fdef decorator1(F):def new_F(a, b):print('This is key')return F(a, b)return new_F@decorator@decorator1def square_sum(a, b):return a**2 + b** 2@decorator1@decoratordef square_diff(a, b):return a**2 - b** 2print(square_sum(3, 4))print(square_diff(3, 4))
运行
/usr/bin/python3.4This is keyinput: 3 425input: 3 4This is key-7
带参数的decorator
#新的包装层def pre_str(pre=''):#以前的decoratordef decorator(F):def new_F(a, b):print(pre + ' :input', a, b)return F(a, b)return new_Freturn decorator@pre_str('Lambda')def square_sum(a, b):return a**2 + b**2@pre_str('Alpha')def square_diff(a, b):return a**2 - b**2print(square_sum(3, 4))print(square_diff(3, 4))
运行
/usr/bin/python3.4Lambda :input 3 425Alpha :input 3 4-7
跳过
def decorator(aClass):class newClass:def __init__(self, age):self.total_display = 0self.wrapped = aClass(age)def display(self):self.total_display += 1print("total display", self.total_display)self.wrapped.display()return newClass@decoratorclass Bird:def __init__(self, age):self.age = agedef display(self):print("My age is",self.age)eagleLord = Bird(5)for i in range(3):eagleLord.display()