无参数的装饰器
def welcome(fn):
def wrapper(*args, **kwargs):
print("welcome")
x = fn(*args, **kwargs)
return x
return wrapper
@welcome
def hello(name: str):
return f"hello %s" % name
print(hello("java"))
输出:
welcome
hello java
有参数的装饰器
def welcome(name: str):
def hh(fn):
def wrapper(*args, **kwargs):
print(f"welcome %s" % name)
x = fn(*args, **kwargs)
return x
return wrapper
return hh
@welcome("python")
def hello(name: str):
return f"hello %s" % name
print(hello("java"))
输出
welcome python
hello java
本文详细讲解了Python中装饰器的使用,包括无参数装饰器`@welcome`实例和带参数装饰器`@welcome(python)`的应用,以及它们在函数调用中的作用。
603

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



