如何在不更改基类的情况下向类的实例添加行为
发布时间:2020-12-20 13:46:56 所属栏目:Python 来源:网络整理
导读:我在代码中从第三方库获得了一个类实例 i = x.get_instance() 然后我的代码从这个实例调用一个方法. i.method_a() 这会在我想要添加行为的类中调用一个方法. 我现在找到的唯一方法是 class BetterClass(ThirdPartyClass): def getMessage(self): message = s
我在代码中从第三方库获得了一个类实例
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是一个instancemethod: >>> 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. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |