Python 函数修饰器
# 一、用函数修饰函数 #!/usr/bin/python3 def decorate_func(func): def call(*args, **kwargs): print('you have called %s()' % (func.__name__)) func(*args, **kwargs) return call @decorate_func def func(name): print('I am not a party member.my name is %s.' % (name)) func(name='Tom')
# 二、用函数修饰类 #!/usr/bin/python3 def decorate_class(aClass): def call(*args, **kwargs): print('you have create a %s class, its name is %s.' % (aClass.__name__, args[0])) return aClass(*args, **kwargs) return call @decorate_class class People(): def __init__(self, name): self.name = name def print(self): print('My name is %s.' % (self.name)) a = People('Tom') b = People('Jerry')
# 三、用函数修饰类方法 #!/usr/bin/python3 def decorate_method(func): def call(*args, **kwargs): print('you have called %s().' % (func.__name__)) func(*args, **kwargs) return call class aClass(): def __init__(self, name): self.name = name @decorate_method def print(self): print('My name is %s.' % (self.name)) a = aClass('Jerry') a.print()
# 四、用类修饰函数 #!/usr/bin/python3 class decorate_func(): def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): print('youhave called %s().' % (self.func.__name__)) self.func(*args, **kwargs) @decorate_func def func(name): print('My name is %s.' % (name)) func('Bob')
# 五、用类修饰类 #!/usr/bin/python3 class decorate_class(): def __init__(self, aClass): self.aClass = aClass def __call__(self, *args, **kwargs): print('You have created a %s class.' % (self.aClass.__name__)) return self.aClass(*args, **kwargs) @decorate_class class People(): def __init__(self, name): self.name = name def print(self): print('My name is %s .' % (self.name)) a = People('Tom')
# 六、匿名函数作为函数修饰器 #~/usr/bin/python3 def attrsetter(attr, value): """ Return a function that sets ``attr`` on its argument and returns it. """ return lambda method: setattr(method, attr, value) or method def depends(*args): if args and callable(args[0]): args = args[0] elif any('id' in arg.split('.') for arg in args): raise NotImplementedError("Compute method cannot depend on field 'id'.") return attrsetter('_depends', args) class People(): def __init__(self, name): self.name = name # 这里用的是函数修饰器,但不是depends函数,而是depends函数执行完之后返回的匿名函数作为函数装饰器 @depends('test') def print(self): print('My name is %s .' % (self.name, )) a = People('Tom') a.print() print(a.print.__dict__)