1: Ordinary ornaments
- Concept: without changing the internal code of the original function, a function is automatically executed before and after the function is executed, adding a function to an existing object
- Format for Ordinary Decorators
def Outer layer function(parameter) def Inner Function(*args,**kwargs) #Before function execution data= parameter(*args,**kwags) #After function execution return data return Inner Function
- Example usage:
def func(arg): def inner(): v = arg() return v return inner # Step One:implement func Function and pass the following function as a parameter, Amount to:func(index) # Step 2: take func The returned value is reassigned to the following function name index = func(index) @func #@Grammar for Decorators def index(): print(123) return 666 print(index)
- Application examples
#Example:Calculate function execution time import time def base(func): def inner(): start_time = time.time() --->#Before function execution v= func() end_tme = time.time() ---->#After function execution print(end_time-start_time) return v return inner @base def func1(): time.sleep(2) # Function execution delayed 2 seconds print(123) @base def func2(): time.sleep(1) print(456)
- About return values
def base(func): def inner(*args,**kwargs): data = func(*args,**kwargs) return data return inner @x1 def index(): print(123) return 666 v1 =index() print(v1) #func Function with parentheses,implement index function,Print first'123',First return 666 to data,data Return to v1
- About front and back
def base(func): def inner(*args,**kwargs) print('Before function call') data = func(*args,**kwargs) #Execute the original function and get the return value print('After calling the original function') return data return inner @base def index() print(123) index()
2: Decorators with parameters
- Basic Format
def base(counter): def wrapper(func): def inner(*args,**kwargs): data = func(*args,**kwargs) # Execute the original function and get the return value return data return inner return wrapper @base(9) def index(): pass #Execute First base function,Then the value will be returned wrapper Return,Become an ornament without parameters
- Example usage
#Write a letter with parameters,Realization:What are the parameters,How many times will the decorated function be executed,Returns the result of the last execution def base(counter): def wrapper(func): def inner(*args,**kwargs): for i in range(counter): data = func(*args,**kwargs) # Execute the original function and get the return value return data return inner return wrapper @base(5) def index(): return So hard! v = index() print(v)
Generator (Variation of Function)
- Concept: If yield exists in a function, then it is a generator function. Calling the generator function returns a generator. The generator's internal code is executed only when the generator is in a for loop, and each loop gets the value returned by yield.
- Generator function: whether yield is included internally
def func(): print('F1') yield 1 print('F2') yield 2 print('F3') #Function internal code will not execute,Returns a generator object v1 = func() #Generators can be for loop,Execution begins once loop function internal code is started for item in v1: print(item) # F1 1 F2 2 F3
- Special Iteration Objects
def func(): yield 1 v = func() result = v.__iter__() print(result)
Fourth: Iterators
- Concept: Get elements one by one from an object (an object created by the str/lsit/tuple/dict/set class) as if it had u nest_ methods and would get elements from an Iterable object each time it was called
- List to Iterator
-
v1 = iter([1,2,3,4])
-
v2 = [1,2,3,4].__iter__()
-
- The iterator wants to get each element: call Val = v1. u next_() repeatedly
v1 = "alex" v2 = iter(v1) while True: try: val = v2.__next__() print(val) except Exception as e: break
- Until error: stoplteration error, indicating that iteration is complete
- How to determine if an object is an iterator: is there a u next_u method inside?
- for loop
v1 = [11,22,33,44] # 1.The internal meeting will v1 Convert to Iterator # 2.Internal Repeat Iterator.__next__() # 3.Finish without error for item in v1: print(item)
- Iterable Objects
-
Internal with _iter_u method and returning an iterator
-
Can be looped for
-
5. Derivation
-
List derivation (also called list generation)
-
Basic Format
v1 = [i for i in Iterable object] v2 = [i for i in iterative object if condition] #condition true before append
-
#Example v1 = [99 if i>5 else 66 for i in range(10)] v2 = [lambda : 100 for i in range(10)] result = v5[9]() # 100 v3 = [lambda :i for i in range(10)] result = v7[5]() # 9 v4 = [lambda x:x*i for i in range(10)] # 1.Excuse me? v4 What is it? Function Address # 2.Excuse me? v4[0](2) What is the result? 18 def num(): return [lambda x:i*x for i in range(4)] # num() -> [function,function,function,function] print([ m(2) for m in num() ]) # [6,6,6,6] #####screen##### v = [i for i in range(10) if i > 5]
- Set Derivation
v1 = { i for i in 'alex' }
- Dictionary derivation
v1 = { 'k'+str(i):i for i in range(10) }