Chapter 3 python3, python3
As we mentioned earlier, in python, everything is an object. A function is also an object, and a function object can be assigned to a variable. A function can also be called through a variable. For example:
def sayHello(name): print(name + ' hello')fn = sayHellofn('roy')
The above code outputs:
roy hello
The function object has a _ name _ attribute. You can get the function name:
def sayHello(name): print(name + ' hello')f =sayHelloprint(f.__name__)print(sayHello.__name__)
The above code outputs:
sayHellosayHello
You will find that the variable f in the previous example also obtains the sayHello function, and essentially it is the sayHello function.
If I want to print a sentence before the sayHello () function is called, you may immediately think of adding a print in the function implementation. This can certainly achieve the effect, but it also modifies the definition of the function.
In fact, many times we want to enhance the function without modifying the function definition. This method of dynamically adding a function during code running is called the Decorator ).
The decorator is actually an executable function that uses a function as a parameter and returns a replacement function. Let's start with a simple one:
Def log (fn): def inner (): print ('before fn call ') fn () return innerdef sayHello (): print ('say hello ') decorated = log (sayHello) decorated ()
The above code outputs:
Say hello before calling fn
We can say that the variable decorated is the sayHello decoration version-that is, sayHello is added with something. In fact, if you write a practical decorator, you may want to use the decoration version instead of sayHello, so that you can always get the sayHello version with other things. Without learning any new syntax, you can easily do this by assigning values to variables that contain functions:
Def log (fn): def inner (): print ('before fn call ') fn () return innerdef sayHello (): print ('say hello ') sayHello = log (sayHello) sayHello ()
The above code outputs:
Say hello before calling fn
Now, any call to sayHello () won't get the original sayHello, but the new decorator version! Do you understand?
Now this sayHello function does not contain parameters. How can I write it if it has parameters? View instances:
Def log (fn): def inner (name): print ('before fn call ') fn (name) return innerdef sayHello (name): print (name, 'Say hello ') sayHello = log (sayHello) sayHello ('roy ')
The above code outputs:
Roy say hello before calling fn
In the preceding code example, a wrapped function is used to replace the variable containing the function to implement the decoration function:
sayHello = log(sayHello)sayHello('roy')
In Python3, you can add a modifier name and @ symbol before the function definition to encapsulate the function. For example:
Def log (fn): def inner (name): print ('before calling fn ') fn (name) return inner @ logdef sayHello (name): print (name, 'Say hello') sayHello ('roy ')
The above code outputs:
Roy say hello before calling fn
It is worth noting that this method is no different from simply replacing the original variable with the return value of the log function-Python just adds some syntactic sugar to make it look clearer.
We have written a decorator above, but it is hard-coded and only applicable to specific types of functions-functions with 1 parameter. The inner of the internal function receives one parameter, and then transmits the parameter to the function in the closure. What if we want a decorator that can apply any function? This means that the decorator must receive the call information of any function it decorated and pass any parameters passed to the decorator when calling these functions, fortunately, python provides such a syntax. Let's write a general decorator:
Def log (fn): "General decorator: param fn: return:" "def inner (* args, ** kwargs ): print ('call % s' before '% fn. _ name _) fn (* args, ** kwargs) return inner @ logdef sayHello (name): print (name, 'Say hello') @ logdef sayGoodbye (): print ('say goodbye ') @ logdef sayMessage (name, message): print (name, 'say', message) sayHello ('roy') print () sayGoodbye () print () sayMessage ('roy ', 'Hello World ')
The above code outputs:
Before calling sayHello, roy say hello. Before calling sayGoodbye, say goodbye, before calling sayMessage, roy say Hello World.
Note: when defining a function, * args can be used to retrieve the location parameter from the iterator when calling the function, or to receive additional location parameters when defining the function. Using ** kwargs to indicate that all uncaptured keyword parameters will be stored in the dictionary kwargs. Previously, both args and kwargs were not part of the syntax in Python, but using these two variable names during function definition is a convention. Like *, you can use it when calling and defining functions **
However, there is another problem. Because the log function is a Decorator and returns a function, the original sayGoodbye function still exists, only the sayGoodbye variable with the same name now points to the new function, so the new function will be executed when sayGoodbye () is called, that is, the inner function returned in the log function. But when you look at the functions decorated by the log function, their _ name _ has changed from the original 'saygoodbye 'to 'inner:
Def log (fn): "General decorator: param fn: return:" "def inner (* args, ** kwargs ): print ('call % s' before '% fn. _ name _) fn (* args, ** kwargs) return inner @ logdef sayGoodbye (): print ('say goodbye ') print (sayGoodbye. _ name __)
The above code outputs:
inner
Because the function name returned by the log function is 'inner ', you must copy the _ name _ attribute of the original function to the inner function. Otherwise, some code execution that depends on the function signature will fail.
You do not need to write inner. _ name _ = fn. python built-in functools. wraps does this. Therefore, a complete decorator statement is as follows:
Import functools
Def log (fn): "" common decorator: param fn: return: "@ functools. wraps (fn) def inner (* args, ** kwargs): print ('before % s' call '% fn. _ name _) fn (* args, ** kwargs) return inner @ logdef sayGoodbye (): print ('say goodbye ') print (sayGoodbye. _ name __)
The above code outputs:
sayGoodbye
If the Decorator itself needs to input parameters, what should we do? Then you need to write a higher-order function that returns the decorator, which is more complicated to write. For example, to customize the log text:
Import functoolsdef log (msg): def decorator (fn): "common decorator: param fn: return:" "@ functools. wraps (fn) def inner (* args, ** kwargs): print ('before % s' call '% fn. _ name _) print ('msg: ', msg) fn (* args, ** kwargs) return inner return decorator @ log ('this is a custom message ') def sayGoodbye (): print ('say goodbye ') sayGoodbye ()
The above code outputs:
Before calling sayGoodbye, msg: This is a custom message, say goodbye.