【发布时间】:2021-10-24 06:28:22
【问题描述】:
我创建了一个装饰器,用于管理日志记录。我希望在装饰函数运行之前和之后进行日志记录。当与非常基本的函数交互时,该函数可以正常工作,但是,当与其他类的一部分的方法交互时,事情就会中断。我怀疑这个问题是因为有 2 个self 参数。你知道如何解决它吗?
简化的装饰器类
class Logger:
def __init__(self, logging_type:str = 'debug'):
self.logging_type = logging_type
def __call__(self, decorated_function:callable):
self.func = decorated_function
return getattr(self, self.logging_type)
def debug(self, *args, **kwargs):
print("starting function")
output = self.func(*args, **kwargs)
print("Completing Function")
return output
我们看到装饰器在基本功能上起作用:
@Logger(logging_type="debug")
def simple_function(x):
return x**2
In [2]: simple_function(3)
starting function
Completing Function
Out[2]: 9
但是,与其他类一起使用时会失败:
class BigClass:
def __init__(self, stuff = 10):
self.stuff = stuff
@Logger(logging_type="debug")
def cool_function(self, input1: int):
return self.stuff + input1
In [16]: test = BigClass()
...: test.cool_function(3)
starting function
然后在输出行遇到类型错误:
TypeError: cool_function() missing 1 required positional argument: 'input1'
想法?
【问题讨论】:
标签: python python-3.x decorator python-decorators