我想按照描述在我的 Flask 应用程序中记录 MongoEngine 文档 here 。但我也希望能够排除该文档类具有的某些属性。
如果我给装饰器的apply函数一个额外的参数excludes
不再给出 cls 参数。
Traceback (most recent call last):
File ".../test.py", line 26, in <module>
@__log_update.apply(excludes=[])
TypeError: apply() missing 1 required positional argument: 'cls'
在简化的代码中
def handler(*events):
"""
Signal decorator to allow use of callback functions as class decorators.
"""
def decorator(fn):
def apply(cls, excludes=[]):
for exclude in excludes:
print(exclude)
for event in events:
event.connect(fn, sender=cls)
return cls
fn.apply = apply
return fn
return decorator
@handler()
def __log_update(*args, **kwargs):
pass
@__log_update.apply(excludes=['testString'])
class Test(object):
testString = ''
testInt = 0
但是当只使用 @__log_update.apply
时如果没有任何参数,则给出 cls 参数,且为 <class '__main__.Test'>
正如它应该的那样。
我需要两者来进行日志记录。
最佳答案
关于装饰器的工作原理。
当你像这样应用它时(无论带或不带参数):
@__log_update.apply()
调用的结果应该是一个装饰器本身,然后应用于底层类。
您需要一个额外的层来使 .apply()
函数返回类装饰器:
def handler(*events):
"""
Signal decorator to allow use of callback functions as class decorators.
"""
def decorator(fn):
def apply(excludes=[]):
def class_decor(cls):
for exclude in excludes:
print(exclude)
for event in events:
event.connect(fn, sender=cls)
return cls
return class_decor
fn.apply = apply
return fn
return decorator
@handler()
def __log_update(*args, **kwargs):
pass
@__log_update.apply(excludes=['testString'])
class Test(object):
testString = ''
testInt = 0
关于python - 向装饰器添加参数会删除 cls 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58300941/