Python:覆盖未知类
考虑这个例子:
x = a.some_class_instance
x.foo()
我想装饰 x.foo()
一些东西,类似于
@x.foo()
def dec()
print 'decorator'
x.foo()
是否有办法做到这一点? 谢谢 :)
Consider this example:
x = a.some_class_instance
x.foo()
I want to decorate x.foo()
something along the lines of
@x.foo()
def dec()
print 'decorator'
x.foo()
Is there anyway to do this?
Thanks :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简单的方法是这样做:
另一种方法是扩展实例的类
但我看不出有任何好的理由这样做。
The easy way is to do this:
Another way is to extend the instance's class
But I can't see any good reason to do that.
下面的代码
只是
装饰器的简写,它只接受一个函数作为参数并返回一个新函数。
您的示例代码将编译,并且实际上可以无错误地运行,具体取决于 x.foo 的操作。但我非常怀疑它会做你想做的事。我认为你想要的是:
The following code
is merely shorthand for
A decorator just takes a function as an argument and returns a new function.
Your example code will compile, and could actually run without errors depending on what x.foo does. But I highly doubt it would do what you want. I think what you want is something along the lines of: