Python 函数修饰器

2022/7/30 1:29:25

本文主要是介绍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__)

 



这篇关于Python 函数修饰器的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程