Closures and decorators in Python

Closures and decorators in Python


Refer to "Python3 from entry to actual combat"

1. What is a closure?

(1) Closure: return another function object in one function (such as nested function)
(2) Nested function: functions defined in other functions are called nested functions, or local functions

	def print_msg():
        msg = "hello"
        def printer():#这是嵌套函数
            print('I am a local funtion')
            print(msg)
        printer()
    print_msg()
    运行结果如下:
    '''
    I am a local funtion
    hello
    '''
	def print_msg():
        msg = "hello"
        def printer():
            print('I am a local funtion ')
            print(msg)
        return printer#返回了另一个函数对象,这就是闭包(看定义)
    p = print_msg()
    p()

	运行结果如下:
    '''
    I am a local funtion 
    hello
    '''

(3) For a class with only one function, or when a function needs to use the data in its surrounding environment, you can consider using closures

	def Exp(a):
        def Power(b):
            return a**b
        return Power
    exp = Exp(10)
    print(exp(3)) 
    运行结果如下:
    '''
    1000
    '''

Second, the decorator

Is equivalent to adding a little new function to your function

	import time#导入时间模块
    def decorator(func):
        def wrapper():
            print("现在时间{}".format(time.time()))
            func()
            print("现在时间{}".format(time.time()))
        return wrapper 
    
    @decorator #相当于say=decorator(say)
    def say():
        print("这里是教学")
        
    @decorator 
    def hello():
        print("hello!")
        
    say()
    hello()
    运行结果如下:
    '''
    现在时间1603175839.9921477
    这里是教学
    现在时间1603175839.9921477
    现在时间1603175839.9921477
    hello!
    现在时间1603175839.9931438
    '''
	def decorator(func):
        def wrapper(Name):
            func(Name)
        return wrapper
    
    @decorator
    def say(name):#相当于把wrapper返回给了say函数,而name直接传给了Name,调用fun(就是你原来的say函数),输出一些值
        print("{},你好".format(name))
        
    @decorator
    def hello(name):
        print("hello,{}".format(name))
        
    say('wang')
    print()
    hello('zhang')
	运行结果如下:
    '''
    
    wang,你好
    
    hello,zhang
    '''
	def decorator_wrapper(arg,arg2):
        def decorator(func):
            def wrapper(Name):
                print(arg)
                func(Name)
                print(arg2)
            return wrapper
        return decorator
    
    @decorator_wrapper(arg='welcome',arg2='have a good time')#将这个理解为多传了两个参数,其他和之前的一样
    def say(name):
        print(name,"你好")
        
    @decorator_wrapper(arg="你好",arg2='祝你幸福')
    def hello(name):
        print(name,"hello")  
    say("张")
    hello("王")
    
	运行结果如下:
    '''
    welcome
    张 你好
    have a good time
    你好
    王 hello
    祝你幸福
    '''
	def decorator_wrapper(arg,arg2):
        def decorator(func):
            def wrapper(name,*args,**kwargs):
                print(arg)
                func(name,*args,**kwargs)
                print(arg2)
            return wrapper
        return decorator
    
    @decorator_wrapper(arg='weicome', arg2='have a good time')
    def say(name,*args,**kwargs):
        print(name)
        print('可变参数:',end = " ")
        for e in args:
            print(e,end='')
        
        print("\n字典参数",end = " ")
        for key in kwargs:
            print(key,kwargs[key],end=' ')
        print()#用于换行
            
            
            
    say('wang',23,'shanghai',python=78,ds=90)

	运行结果如下:
    '''
    weicome
    wang
    可变参数: 23shanghai
    字典参数 python 78 ds 90 
    have a good time
    '''

The decorator is not only a function, but also a class, that is, a decorator class is used to wrap a function to add functionality to the function. The class decorator mainly relies on the __call__() method of the class. When using the @ form, it will decorate This method is called when the device is attached to the function

	class decorator(object):#装饰器类
        def __init__(self,func):
            self.func = func
            
        def __call__(self,name,*args,**kwargs):
            print('class decorator start')
            self.func(name,*args,**kwargs)#这里加不加return都一样,直接执行也行
        
    @decorator
    def say(name,*args,**kwargs):
        print(name)
        print('可变参数:',end = ' ')
        for e in args:
            print(e,end = " ")
        print("\n字典参数:",end=" ")
    
        for key in kwargs:
            print(key,kwargs[key],end = " , ")
            
            
    say('wang',23,'sb',lover="w ")
	运行结果如下:
    '''
    class decorator start
    wang
    可变参数: 23 sb 
    字典参数: lover w , 
    '''

Guess you like

Origin blog.csdn.net/qq_45911278/article/details/111829945