作者:lql | 来源:互联网 | 2024-11-26 13:53
在 Python 编程中,装饰器(Decorator)是一种特殊类型的函数,它可以修改其他函数的功能或行为,而无需直接改变这些函数的代码。装饰器通常用于添加功能,如日志记录、性能测试、事务处理等。
### 装饰器示例
import time
def math_type(type='add'):
def decorator_time(func):
def wrapper(*args, **kwargs):
print(f'Operation type: {type}')
start_time = time.time()
print(f'Start time: {start_time}')
result = func(*args, **kwargs)
end_time = time.time()
print(f'End time: {end_time}')
print(f'Total time: {end_time - start_time} seconds')
return result
return wrapper
return decorator_time
@math_type('add')
def add_numbers(*args, **kwargs):
total = 0
for num in args:
total += num
for key, value in kwargs.items():
total += value
return total
@math_type('subtract')
def subtract_numbers(*args, **kwargs):
total = 0
for num in args:
total -= num
for key, value in kwargs.items():
total -= value
return total
# 测试装饰器
result_add = add_numbers(12, 3, a=5, b=3)
print(f'Result of addition: {result_add}')
result_subtract = subtract_numbers(12, 3, a=5, b=3)
print(f'Result of subtraction: {result_subtract}')
### 装饰类示例
装饰类类似于装饰器,但它们用于类而不是函数。装饰类可以在类实例化时添加额外的功能或属性。
def decorate_class(original_class):
class NewClass:
def __init__(self, *args, **kwargs):
self.total_display = 0
self.wrapped = original_class(*args, **kwargs)
def display(self):
self.total_display += 1
print(f'Total displays: {self.total_display}')
self.wrapped.display()
return NewClass
@decorate_class
class Bird:
def __init__(self, age):
self.age = age
def display(self):
print(f'My age is: {self.age}')
# 创建并测试装饰类
bird_instance = Bird(5)
for _ in range(3):
bird_instance.display()
通过上述示例,我们可以看到装饰器和装饰类如何在不修改原始代码的情况下,为函数和类添加新的功能。这对于提高代码的可维护性和复用性非常有帮助。