python - 如何在不更改基类的情况下向类的实例添加行为

标签 python

我在我的代码中从第三方库中获取类的实例

i = x.get_instance()

然后我的代码从这个实例调用一个方法。

i.method_a() 

这将在我想添加行为的此类中调用一个方法。

我现在找到的唯一方法是

class BetterClass(ThirdPartyClass):
    def getMessage(self):
        message = super(BetterClass, self).getMessage()
        ... add behaviour
        return message    

i.__class__ = BetterClass
i.method_a()

但是添加这种行为的更好方法是什么,因为我无法更改我返回的实例。 我自己没有初始化

最佳答案

你可以这样做:

>>> class Example(object):
...   def foo(self):
...       print "foo"
...
>>> a=Example()
>>> a.foo()
foo
>>>
>>> def new_foo(self):
...    Example.foo(self)
...    print "new"
...
>>> funcType = type(Example.foo)
>>> a.foo = funcType(new_foo, a, Example)
>>> a.foo()
foo
new

在这里,typeclass . funcType 是一个实例方法:

>>> funcType
<type 'instancemethod'>
>>> help(funcType)
...
class instancemethod(object)
 |  instancemethod(function, instance, class)
 |
 |  Create an instance method object.

...

另外,(感谢@bruno desthuilliers),你可以这样做:

a.foo = new_foo.__get__(a, type(a))

而不是使用 funcType

关于python - 如何在不更改基类的情况下向类的实例添加行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27801744/

相关文章:

python - 如何从python中的.sec.gz类型的ftp服务器读取文件

python - 如何使用 Python 中的返回计算最大亏损

python - 对于 matplotlib 子图,Axes.invert_axis() 不适用于 sharey=True

python - 由两个散点曲面之间的交点定义的曲线,以不同方式采样

python - 为什么 NLTK WordNet 无法找到简单的单词?

python - 在范围内创建自定义数字数据类型?

python - 我可以忽略 setuptools MANIFEST.in 中的符号链接(symbolic link)吗?

python - 查找哪个列对于哪个 Excel 工作表数据框是唯一的

python - 安装Python GTK

python - 在 Python 中创建依赖关系图