Adorners as a function of Python can be said to be very important, but also to learn a gateway in Python, probably many people will find it easy to confuse when learning the adorner, the most in the Python core programming and the interpretation of Python feel a little bit clear, here.
The most important feature of the adorner is that, in the case of not modifying the original code, the original code to add functionality, so to write the adorner to comply with two rules:
- Cannot modify the decorated function
- You cannot modify the way a function is called
Trying to figure out what the decorator needs to know.
1. Scope of functions
2. Closures
3. Higher-order functions
4. Nesting functions
The code is as follows:
def fun (name):
def wapper(): print("the test fun is %s" %name) return wapper
A = Fun (test) #<function Fun.<locals>.wapper at 0x0000000002103840>
Type (a) #<class ' function ' >
It can be seen here. Fun (test) is a function of memory address, the program gives a function type
This code can also see a conclusion, that is, the function of a method of variables, then you can well understand the decorative work form
The code is as follows:
Import time
def timer (fun):
def wapper(*args,**kwargs): start_time = time.time() fun() stop_time = time.time() func_time = stop_time - start_time print(‘the fun run time is %s‘ %func_time)return wapper
def test1 ():
time.sleep(3)print(‘the fun1 is test1‘)
test1= Timer (test1)
Print (test1) #<function Timer.<locals>.wapper at 0x00000000025b0488>
Test1 ()
> The FUN1 is test1
>the Fun Run time is 3.0052061080932617
Here we have implemented all the requirements that we need to achieve to write the adorner, and implement the function that the original code function is attached to.
But the real Python has given us a tedious operation like test1 = Timer (test1), Python uses @ instead of what we do, making the code look more elegant and concise so the correct code should be like this
Import time
def timer (fun):
def wapper(*args,**kwargs): start_time = time.time() fun() stop_time = time.time() func_time = stop_time - start_time print(‘the fun run time is %s‘ %func_time)return wapper
@timer
def test1 ():
time.sleep(3)print(‘the fun1 is test1‘)
Test1 ()
@timer
def test2 (name,age):
print("test2", %(name,age))
Test2 (' Chen ', ' 22)
Python Decorator Learn