构建一个装饰器
def uppercase_decorator(function): # 接受一个function作为参数
def wrapper():
func = function() # func即为function的返回值
make_uppercase = func.upper()
return make_uppercase # wrapper函数返回 function返回值 的大写形式
return wrapper # uppercase_decorator函数返回 一个叫做 wrapper 的函数
两种方法使用上述装饰器
一
def say_hi():
return 'hello there'
decorate = uppercase_decorator(say_hi) # 把say_hi这个函数作为参数传到uppercase_decorator函数
## 执行过程如下
# def uppercase_decorator(function): # 接受say_hi作为参数
# def wrapper():
# func = function() # say_hi的返回值即'hello there'赋值给func
# make_uppercase = func.upper() # 对 'hello there' 进行大写转换
# return make_uppercase # wrapper函数返回 'HELLO THERE'
# return wrapper # uppercase_decorator函数返回 一个叫做 wrapper 的函数, 而 wrapper的返回值正是 'HELLO THERE'
decorate() # decorate 正是上述的wrapper函数,对其加()即调用,故返回 'HELLO THERE'
# 'HELLO THERE'
二
第二种方式从表达上更像重写了say_hi函数,使其增加了一个返回值大写的功能
@uppercase_decorator
def say_hi():
return 'hello there'
say_hi()
# 'HELLO THERE'
多个装饰器
def split_string(function):
def wrapper():
func = function()
splitted_string = func.split()
return splitted_string
return wrapper
# ----------------------------------
@split_string
@uppercase_decorator
def say_hi():
return 'hello there'
say_hi()
# ['HELLO', 'THERE']
构建一个可以传参的装饰器
注意:参数传给 wrap 函数
def decorator_with_arguments(function):
def wrapper_accepting_arguments(arg1, arg2):
print("My arguments are: {0}, {1}".format(arg1,arg2))
function(arg1, arg2)
return wrapper_accepting_arguments
@decorator_with_arguments
def cities(city_one, city_two):
print("Cities I love are {0} and {1}".format(city_one, city_two))
# 将cities(city_one, city_two)传给decorator_with_arguments 得到wrapper_accepting_arguments函数
# wrapper_accepting_arguments函数
# 1. 执行 print("My arguments are: {0}, {1}".format(arg1,arg2))
# 2. 执行 function(arg1, arg2), 即 print("Cities I love are {0} and {1}".format(city_one, city_two))
cities("Nairobi", "Accra")
# My arguments are: Nairobi, Accra
# Cities I love are Nairobi and Accra
构建一个通用模板
def a_decorator_passing_arbitrary_arguments(function_to_decorate):
def a_wrapper_accepting_arbitrary_arguments(*args,**kwargs):
print('The positional arguments are', args)
print('The keyword arguments are', kwargs)
function_to_decorate(*args)
return a_wrapper_accepting_arbitrary_arguments
@a_decorator_passing_arbitrary_arguments
def function_with_no_argument():
print("No arguments here.")
function_with_no_argument()
# The positional arguments are ()
# The keyword arguments are {}
# No arguments here.
@a_decorator_passing_arbitrary_arguments
def function_with_arguments(a, b, c):
print(a, b, c)
function_with_arguments(1,2,3)
# The positional arguments are (1, 2, 3)
# The keyword arguments are {}
# 1 2 3
@a_decorator_passing_arbitrary_arguments
def function_with_keyword_arguments():
print("This has shown keyword arguments")
function_with_keyword_arguments(first_name="Derrick", last_name="Mwiti")
# The positional arguments are ()
# The keyword arguments are {'first_name': 'Derrick', 'last_name': 'Mwiti'}
# This has shown keyword arguments