Python函数的装饰器用法
发布时间:2023-12-03 19:11:59
Python函数的装饰器是一种高级的语法和功能特性,是Python语言中非常强大和灵活的工具。装饰器可以用于在函数运行前后,动态地修改或增加函数的功能,而不需要修改被装饰函数的源代码。这种特性非常有利于代码的重用性和可维护性。
装饰器的用法有很多种,下面我将详细介绍几个常见的装饰器用法。
1. 函数装饰器:函数装饰器是在函数运行之前或之后对函数进行修饰的装饰器。例如,我们可以使用装饰器在函数运行之前检查函数的参数是否合法,或在函数运行之后对函数的返回值进行处理。
def decorator(func):
def wrapper(*args, **kwargs):
# 在运行函数之前的
print("Before function is called")
# 运行函数
result = func(*args, **kwargs)
# 在运行函数之后的
print("After function is called")
return result
return wrapper
@decorator
def my_function():
print("Function is called")
my_function() # 输出:Before function is called
# Function is called
# After function is called
2. 类装饰器:类装饰器是对类进行修饰的装饰器。类装饰器可以在类实例化之前或之后对类进行修改或增加功能。
def decorator(cls):
class Wrapper:
def __init__(self, *args, **kwargs):
# 在类实例化之前的
print("Before class is created")
self.wrapped = cls(*args, **kwargs)
# 在类实例化之后的
print("After class is created")
def __getattr__(self, name):
return getattr(self.wrapped, name)
return Wrapper
@decorator
class MyClass:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hello, {self.name}")
my_obj = MyClass("John") # 输出:Before class is created
# After class is created
my_obj.greet() # 输出:Hello, John
3. 带参数的装饰器:装饰器可以接受参数,这样可以更加灵活地定制装饰器的功能。
def decorator(arg1, arg2):
def wrapper(func):
def inner_wrapper(*args, **kwargs):
print(f"Decorator arguments: {arg1} {arg2}")
result = func(*args, **kwargs)
print("Decorator finished")
return result
return inner_wrapper
return wrapper
@decorator("arg1_value", "arg2_value")
def my_function():
print("Function is called")
my_function() # 输出:Decorator arguments: arg1_value arg2_value
# Function is called
# Decorator finished
在上面的例子中,装饰器decorator接受两个参数arg1和arg2,返回一个内部装饰器wrapper。内部装饰器inner_wrapper接受被装饰函数的参数,并在运行函数前后打印出装饰器的参数。
装饰器是Python中非常强大和灵活的工具,可以通过装饰器来扩展和定制函数和类的功能。掌握装饰器的用法,可以提高代码的可读性和可维护性,同时也促进了函数和类的代码重用。希望上述示例对你有所帮助。
