开发者

How to apply a Python timings decorator to a method within a class

I am trying to apply the timing decorator described here to a method within a class instead of a standalone method. How should this be done?

I am getting this error:

TypeError: unbound method wrapper() must be called with SomeClass instanc开发者_运维技巧e as
first argument (got float instance instead)


EDIT

Thanks to your comment, I think I know what the problem is. This doesn't work:

class A:

    @timings
    @classmethod
    def a(cls, x):
       print(x)

A.a(2)

for exactly the reason you said. TypeError: unbound method wrapper() must be called with A instance as first argument (got int instance instead)

But this does:

class A:

    @classmethod
    @timings
    def a(cls, x):
        print(x)

A.a(2)

So the order matters. I think what's going on here is that it's fooling the way python handles bound methods: When python looks at the member a, it has to make a decision:

  1. Make a bound method
  2. Make a class method
  3. Do nothing (leave it as it is)

If it gets a regular function, it will do (1), and @timings produces a regular function.

Does this solve the problem?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜