Python:覆盖未知类

发布于 2024-12-02 10:32:16 字数 238 浏览 0 评论 0原文

考虑这个例子:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浴红衣 2024-12-09 10:32:16

简单的方法是这样做:

x.foo = dec(x.foo)

另一种方法是扩展实例的类

x = a.some_class_instance
class Extended(x.__class__):
    @dec
    def foo(...):
        ...

但我看不出有任何好的理由这样做。

The easy way is to do this:

x.foo = dec(x.foo)

Another way is to extend the instance's class

x = a.some_class_instance
class Extended(x.__class__):
    @dec
    def foo(...):
        ...

But I can't see any good reason to do that.

Smile简单爱 2024-12-09 10:32:16

下面的代码

@decorator
def decoratee():
    pass

只是

def decoratee():
    pass
decoratee = decorator(decoratee)

装饰器的简写,它只接受一个函数作为参数并返回一个新函数。

您的示例代码编译,并且实际上可以无错误地运行,具体取决于 x.foo 的操作。但我非常怀疑它会做你想做的事。我认为你想要的是:

def decorate(f):
    def decorated():
        print 'decorator'  
        f()
    return decorated
x.foo = decorate(x.foo)

The following code

@decorator
def decoratee():
    pass

is merely shorthand for

def decoratee():
    pass
decoratee = decorator(decoratee)

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:

def decorate(f):
    def decorated():
        print 'decorator'  
        f()
    return decorated
x.foo = decorate(x.foo)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文