Decorator is a design pattern , Play a decorative role . Namely Without modifying the function code , Add some functions to the function .
There is a function that returns a string , Without modifying the function , Convert the returned string to uppercase string .
def uppercase_decorator(func): # Define a function , Its parameters func Is a function type parameter
def inner(): # Nested function inner
s = func() # call func() Function and assign the return value to s Variable
make_uppercase = s.upper() # Convert the string to uppercase and assign it to make_uppercase
return make_uppercase # End nested function func() call , Returns the converted String
return inner # End function uppercase_decorator() call , Return nested functions inner
def say_hello():
return 'hello world.'
if __name__=="__main__":
say_hello2 = uppercase_decorator(say_hello) # call uppercase_decorator() function , The argument is say_hello() function , Return value say_hello2 A variable is also a function
print(say_hello2()) # call say_hello2 function
Python Provides decorator annotation function , The decorator is essentially a function .
The above code is modified as follows using the decorator :
def uppercase_decorator(func):
def inner():
s = func()
make_uppercase = s.upper()
return make_uppercase
return inner
@uppercase_decorator # Use @uppercase_decorator Decorator statement say_hello1() function
def say_hello1():
return "zhang cheng."
if __name__=="__main__":
print(say_hello1()) # Using decorators does not require explicit calls uppercase_decorator() function , Call directly say_hello1() Function .
A function can have multiple decorator declarations .
def uppercase_decorator(func): # Convert strings to uppercase
def inner():
s = func()
make_uppercase = s.upper()
return make_uppercase
return inner
def backet_decorator(func): # Add parentheses to the string
def inner():
s = func()
make_bracket = '(' + s + ')'
return make_bracket
return inner
@backet_decorator
@uppercase_decorator
def say_hello():
return 'hello world.'
if __name__=="__main__":
print(say_hello())
Decorators are essentially functions , So you can pass parameters to the decorator .
def calc(func): # Define decorator functions calc(func), Its parameter is also a function
def wrapper(arg1): # Defining nested functions wrapper(arg1), This function parameter list is consistent with the function parameter list to be annotated by the decorator
return func(arg1)
return wrapper
@calc
def square(n):
return n * n
@calc
def abs(n):
return n if n > 0 else -n
if __name__=="__main__":
print(f"3's square is {
square(3)}")
print(f"-30's absulate is {
abs(-30)}")