要比较一个封装的函数是否是装饰器的实例,可以使用inspect
模块来获取函数的定义信息,并检查函数是否包含装饰器。
下面是一个示例代码:
import inspect
def decorator(func):
def wrapper(*args, **kwargs):
print("Before function execution")
result = func(*args, **kwargs)
print("After function execution")
return result
return wrapper
@decorator
def my_function():
print("Inside my_function")
def is_decorator(func):
if inspect.isfunction(func):
source_code = inspect.getsource(func)
return '@' in source_code
return False
print(is_decorator(my_function)) # 输出 True
print(is_decorator(my_function.__wrapped__)) # 输出 False
在上面的示例中,decorator
函数是一个装饰器,它将被装饰的函数包装在内部函数wrapper
中,并在函数执行前后打印信息。my_function
是被decorator
装饰的函数。
is_decorator
函数用于检查一个函数是否是装饰器的实例。它首先使用inspect.isfunction
函数判断参数是否为一个函数对象,然后使用inspect.getsource
函数获取函数的源代码。如果源代码中包含@
符号,则认为该函数是一个装饰器。
在示例中,is_decorator(my_function)
会返回True
,因为my_function
是被decorator
装饰的函数,而is_decorator(my_function.__wrapped__)
会返回False
,因为my_function.__wrapped__
是未被装饰的原始函数。