如何将 Python 计时装饰器应用于类中的方法
我正在尝试应用描述的计时装饰器 这里是类中的方法而不是独立的方法。这应该怎么做呢?
我收到此错误:
TypeError: unbound method wrapper() must be called with SomeClass instance as first argument (got float instance instead)
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 instance as first argument (got float instance instead)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编辑
感谢您的评论,我想我知道问题是什么。这不起作用:
正是出于您所说的原因。
类型错误:必须使用 A 实例作为第一个参数来调用未绑定方法wrapper()(改为使用 int 实例)
但这确实如此:
所以顺序很重要。我认为这里发生的事情是它欺骗了python处理绑定方法的方式:当python查看成员a时,它必须做出决定:
如果它得到一个常规函数,它将执行 (1),并且 @timings 生成一个常规函数。
这能解决问题吗?
EDIT
Thanks to your comment, I think I know what the problem is. This doesn't work:
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:
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:
If it gets a regular function, it will do (1), and @timings produces a regular function.
Does this solve the problem?