我在我的代码中从第三方库中获取类的实例
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
在这里,type
是 class . 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/