Python:强制装饰器继承吗? [英] Python: Force decorator inheritance?
问题描述
我正在使用相当大的OOP代码库,并且希望注入一些跟踪/记录功能。最简单的方法是在一些基类的某些方法周围引入一个装饰器,但是不幸的是装饰器没有被继承。
I'm working with quite a large OOP code-base, and I'd like to inject some tracing/logging. The easiest way to do this would be to introduce a decorator around certain methods on some base classes, but unfortunately decorators aren't inherited.
我确实尝试了以下方法:
I did try something like the following:
def trace(fn):
def wrapper(instance, *args, **kwargs):
result = fn(instance, *args, **kwargs)
# trace logic...
return result
return wrapper
class BaseClass(object):
def __init__(self, ...):
...
self.__call__ = trace(self.__call__) # line added to end of method
...而 __ call __
方法是包装(我可以从将实例信息打印到控制台中看到) wrapper
函数未按预期执行。
...and while the __call__
method is wrapped (which I can see from printing the instance information to the console) the wrapper
function isn't executed as expected.
我还简要地研究了使用基于此答案的元类,但是它很快y破坏了使用自省功能的系统的其他部分,所以我认为这是不可行的。
I also looked briefly at using a metaclass based on this answer, but it instantly breaks other parts of the system that use introspection, so I think that's a no-go.
还有其他方法可以强制这些装饰器在从 BaseClass
继承的类的 __ call __
方法?
Is there any other way I can force the application of these decorators around the __call__
method of classes that inherit from BaseClass
?
推荐答案
为什么元编程会搞乱自省?也许您没有正确使用它?试试这个(假设Python2.x):
Why would metaprogramming mess up introspection? Perhaps you are not using it correctly? Try this (assuming Python2.x):
class MyMeta(type):
def __new__(mcl, name, bases, nmspc):
if "__call__" in nmspc:
nmspc["__call__"] = trace(nmspc["__call__"])
return super(MyMeta, mcl).__new__(mcl, name, bases, nmspc)
class BaseClass(object):
__metaclass__ = MyMeta
然后您可以简单地从 BaseClass
继承,并且 __ call __
将自动被包装。
You can then simply inherit from BaseClass
and __call__
will get wrapped automatically.
我不确定哪种自省会破坏这种情况。除非 BaseClass
实际上不是从对象
继承,而是从实现自己元数据的东西继承? ?但您也可以通过强制 MyMeta
从该父级的meta继承(而不是 type
)来处理这种情况。
I'm not sure what kind of introspection would break that. Unless BaseClass
actually does not inherit from object
but from something that implements its own meta?? But you can deal with that case as well by forcing MyMeta
to inherit from that parent's meta (instead of type
).
这篇关于Python:强制装饰器继承吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!