如何对静态方法进行猴子补丁? [英] How to monkeypatch a static method?

查看:31
本文介绍了如何对静态方法进行猴子补丁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然将实例方法添加到类中相当简单,例如

While it's fairly simple to monkeypatch instance methods to classes, e.g.

class A(object):
    pass

def a(self):
    print "a"

A.a = a

使用另一个类的 @staticmethod à la

doing this with another class's @staticmethod à la

class B(object):
    @staticmethod
    def b():
        print "static b"

A.b = B.b

导致 A.b() 产生一个

TypeError: 未绑定的方法 b() 必须使用 A 实例作为第一个参数调用(什么都没有)

TypeError: unbound method b() must be called with A instance as first argument (got nothing instead)

推荐答案

让 A.b 成为静态方法,你应该没问题:

Make A.b a static method and you should be fine:

A.b = staticmethod(B.b)

这篇关于如何对静态方法进行猴子补丁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆