我们的装饰器,肯定会遇见参数,被带不同参数的函数调用装饰器,那么怎么解决这个问题呢?
在装饰器中使用 *args 可变参数的概念
#装饰器编写
def decorator(func): #传入要在该方法基础上要实现的操作
def wrapper(*args): #传入一个可变参数的值,满足不同函数的调用
print(datetime.datetime.now()) #这是新需求要求增加的新要求
func(*args) #执行之前的方法
return wrapper
@decorator #魅力之处,使用@符号加载装饰器,之后代码直接使用原方法即可,这对在原基础上修改代码非常奏效
def f1():
print("This is a origin function")
@decorator
def f2(weather):
print("This is a origin function2")
@decorator
def f3(weather,wind):
print("This is a origin function3")
f1() #无参数
f2("sun") #1个参数
f3("rain","no") #2个参数
本文介绍了Python装饰器的应用场景及其实现方法,展示了如何通过装饰器为原有函数添加新功能,同时保持函数调用的简洁性。文章通过实例演示了装饰器如何处理不同数量的输入参数。
712

被折叠的 条评论
为什么被折叠?



