Python中的装饰器概念及应用实例
装饰器是Python中一个强大的特性,它允许我们在不改变原函数定义的情况下,为函数添加新的功能或者行为。
装饰器的语法基本形式如下:
@decorator
def original_function():
# function body
例如,我们可以创建一个简单的计数装饰器:
def counter_decorator(func):
count = 0
def wrapper(*args, **kwargs):
nonlocal count
count += 1
return func(*args, **kwargs), count
return wrapper
@counter_decorator
def say_hello(n=1):
for _ in range(n):
print('Hello!')
say_hello() # 输出:Hello! Hello!
在这个例子中,counter_decorator
就是装饰器函数,它接收一个函数作为参数,并返回一个新的包装函数。
还没有评论,来说两句吧...