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__)
复制代码

 

posted @   看一百次夜空里的深蓝  阅读(467)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示