1

我有一个基类,@classmethod它充当许多后代类中大量方法的装饰器。

class BaseClass():
    @classmethod
    def some_decorator(cls, method):
        @wraps(method)
        def inner_method(self, *args, **kwargs):
            # do stuff
            return method(self, *args, **kwargs)
        return inner_method


class ChildClass(BaseClass):
    @BaseClass.some_decorator
    def some_child_method(self):
        # do other stuff
        return

当我分析此代码并通过树视图查看它时,我看到some_decorator来自数百个不同地方的数千个调用。

然后我看到some_decorator回电到数百个它刚刚来自的地方。

这很烦人,我还没有找到解决方法,既不是通过更改代码也不是通过其他方式分析。(使用 gprof2dot atm:How can you get the call tr​​ee with python profilers?

想法?

4

1 回答 1

1

有一些方法可以构建装饰器来保存文档/签名。wrapt 库为此提供了很多功能。

https://wrapt.readthedocs.io/en/latest/decorators.html#decorating-class-methods

它最终看起来像这样:

class BaseClass():
    @wrapt.decorator
    @classmethod
    def some_decorator(cls, method, instance, *args, *kwargs):
        # do stuff
        return method(instance, *args, **kwargs)
于 2017-07-14T17:26:34.943 回答