Home  >  Article  >  Backend Development  >  Introducing Python’s function decorators

Introducing Python’s function decorators

coldplay.xixi
coldplay.xixiforward
2021-01-21 10:05:522297browse

Introducing Python’s function decorators

Related free learning recommendations: python video tutorial

Pyhton’s function decorator can It is very convenient to add functions to the function through the @ method of the decorator function

"""
一.函数用法
"""def sum_list(list):
    """将列表中的数字求和
    输入:含有数字的列表
    list=[2,6,3,2,1]
    sum_list(list)
    """
    sum_=0
    for i in list:
        sum_+=i    return sum_#1.将函数sum_list赋值给变量list_sum,从而产生的新名称函数list_sum()list_sum=sum_list
list_sum([2,5,3,8,6])#2.删除函数del list_sum
list_sum([4,3,5,2])#NameError: name 'list_sum' is not defined#3.函数中定义函数def sum_(list):
    def sum_list(list):
        """将列表中的数字求和
        输入:含有数字的列表
        list=[2,6,3,2,1]
        sum_list(list)
        """
        sum_ = 0
        for i in list:
            sum_ += i        return sum_    return sum_list(list)sum_([3,6,3,2])#4.将函数作为参数传入另一个函数def print_():
    print('好开心!')print_()#定义一个嵌套函数,参数为定义好的函数def deco(function):
    def wrapped():
        print('这个函数被嵌套了')
        function()
    return  wrapped"""
二,函数装饰器
"""#1.用函数装饰器替代嵌套函数if '嵌套函数'=='嵌套函数':
    #定义一个打印函数
    def print_():
        print('好开心!')
    print_()

    #定义一个嵌套函数,参数为定义好的函数
    def deco(function):
        def wrapped():
            print('这个函数被嵌套了')
            function()
        return  wrapped

    print_2=deco(print_)#将嵌套函数的功能赋值给新函数print_2()
    print_2()if '函数装饰器'=='函数装饰器':
    #或者采用装饰器的方法
    def deco(function):
        def wrapped():
            print('这个函数被嵌套了')
            function()
        return  wrapped

    @deco#可以直接将函数deco()嵌套在函数print_()上,形成新的函数
    def print_():
        print('好开心!')
    print_()#2.用一个函数装饰器装饰多个函数def print_name(function):
    """该装饰器函数将为函数增加打印函数名字的功能"""
    import functools#该语句可以使函数被装饰后,函数信息保持不变
    @functools.wraps(function)
    def wrapped(*args,**kwargs):
        """
        *args:表示可传入任意数量的单值对象,函数将自动将其收集在元组中
        **kwargvs:表示可以传入任意数量的字典键值对,比如:value=3,函数将自动收集为字典
        """
        print('函数的名字为%s'%function.__name__)
        return  function(*args,**kwargs)#执行传入参数的函数
    return wrapped

@print_namedef sum_list(list):
    sum_=0
    for i in list:
        sum_+=i    return sum_
sum_list([5,7,3,2])sum_list.__name__#经过检查,函数名称没有发生改变@print_namedef small_value(list):
    return min(list)small_value([4,8,4,2,4])#3.用多个函数装饰器装饰一个函数,靠近函数的装饰器将被优先执行def print_hash(function):
    """该装饰器函数将为函数增加打印函数hash值的功能"""
    def wrapped(*args,**kwargs):
        """
        *args:表示可传入任意数量的单值对象,函数将自动将其收集在元组中
        **kwargvs:表示可以传入任意数量的字典键值对,比如:value=3,函数将自动收集为字典
        """
        print('函数的名字为%s'%function.__hash__)
        return  function(*args,**kwargs)#执行传入参数的函数
    return wrappeddef print_name(function):
    """该装饰器函数将为函数增加打印函数名字的功能"""
    def wrapped(*args,**kwargs):
        """
        *args:表示可传入任意数量的单值对象,函数将自动将其收集在元组中
        **kwargvs:表示可以传入任意数量的字典键值对,比如:value=3,函数将自动收集为字典
        """
        print('函数的名字为%s'%function.__name__)
        return  function(*args,**kwargs)#执行传入参数的函数
    return wrapped#为函数增添打印函数名称和函数值的功能@print_hash
@print_namedef small_value(list):
    return min(list)

Use classes as decorations

#用类作为装饰class FirstDecorator(object):#需要引入object
    def __init__(self,func):
        self.__func=func    def __call__(self, *args, **kwargs):# __call__ 方法可以让函数使用装饰
        import time        print('执行时间:{}'.format(time.ctime(time.time())))
        self.__func(*args)@FirstDecorator#使用类的装饰def print_(*number):
    print(number)print_(5,63,8,4,6,2)

For a large number of free learning recommendations, please visit python tutorial(Video)

The above is the detailed content of Introducing Python’s function decorators. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete