开发者

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

开发者 https://www.devze.com 2023-03-21 23:01 出处:网络
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 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

精彩评论

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

关注公众号