1 装饰器
装饰器(decorators)是 Python 中的一种高级功能,它允许你动态地修改函数或类的行为。
装饰器是一种函数,它接受一个函数作为参数,并返回一个新的函数或修改原来的函数。
语法使用 @decorator_name 来应用在函数或方法上。
Python 还提供了一些内置的装饰器,比如 @staticmethod
和 @classmethod
,用于定义静态方法和类方法。
装饰器的应用场景:
- 日志记录: 装饰器可用于记录函数的调用信息、参数和返回值。
- 性能分析: 可以使用装饰器来测量函数的执行时间。
- 权限控制: 装饰器可用于限制对某些函数的访问权限。
- 缓存: 装饰器可用于实现函数结果的缓存,以提高性能。
1.1 示例一:在函数前后添加输出
# 定义一个以函数为参数的函数
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()
运行结果:
1.2 示例二:带参数的装饰器
def do_twice(func):
def wrapper(*args, **kwargs):
func(*args, **kwargs)
func(*args, **kwargs)
return wrapper
@do_twice
def greet(name):
print(f"Hello {
name}")
greet("World")
运行结果:
1.3 示例三:类装饰器
class DecoratorClass:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print('Decorating', self.func.__name__)
return self.func(*args, **kwargs)
@DecoratorClass
def add(a, b):
return a + b
print(add(1, 2))
运行结果:
1.4 注意:如果有有多个装饰器,则从近到远执行
def decorator1(func):
def wrapper():
print("1")
func()
print("2")
return wrapper
def decorator2(func):
def wrapper():
print("3")
func()
print("4")
return wrapper
@decorator1
@decorator2
def some_function():
print("center")
some_function()
运行结果:
2 异常检测
2.1 异常处理
2.2 抛出异常
使用 raise 语句抛出一个指定的异常。
raise语法格式如下:
raise [Exception [, args [, traceback]]]
示例 1:
x = 10
if