装饰器的基本概念
装饰器实际上是一个函数,它接收一个函数作为参数,并返回一个新的函数。在Python中,使用装饰器可以在不修改原有函数的情况下,动态地增加其功能。装饰器常用于日志记录、权限验证、输入控制等场景。
装饰器的语法
使用装饰器的基本语法相对简单。首先定义一个装饰器函数,然后用“@装饰器名称”来修饰目标函数。例如:
def my_decorator(func):
def wrapper():
print(Something is happening before the function is called.)
func()
print(Something is happening after the function is called.)
return wrapper
@my_decorator
def say_hello():
print(Hello!)
say_hello()
在这个示例中,my_decorator函数对say_hello函数进行了装饰。在调用say_hello时,会首先执行装饰器中的内容,然后才执行原函数。
传入参数的装饰器
装饰器不仅可以应用于不带参数的函数,也可以应用于带参数的函数。当需要传入参数的函数被装饰时,装饰器的定义需要稍作修改。下面是一个带参数的装饰器示例:
def repeat(num_times):
def decorator_repeat(func):
def wrapper(args, kwargs):
for _ in range(num_times):
func(args, kwargs)
return wrapper
return decorator_repeat
@repeat(3)
def greet(name):
print(fHello, {name}!)
greet(Alice)
这里,repeat装饰器接受一个参数num_times,在调用函数时,会根据这个参数多次执行目标函数。
装饰器链
Python还支持多个装饰器同时作用于同一个函数,这被称作装饰器链。多个装饰器会从内向外依次执行。例如:
def bold(func):
def wrapper():
return f{func()}
return wrapper
def italics(func):
def wrapper():
return f{func()}
return wrapper
@bold
@italics
def say_hi():
return Hi!
print(say_hi())
在这个例子中,say_hi会先被italics装饰,然后再被bold装饰。最终,它的输出将包含HTML标签,让文本变成了加粗和斜体。
常见面试题示例
在面试中,面试官可能会问一些关于装饰器的具体问题,比如:
通过充分的准备和对装饰器的深入理解,你可以在面试中自信地应对这部分内容。
暂无评论内容