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:
- Make a bound method
- Make a class method
- 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?
精彩评论