2016-05-12 65 views
0

比方说,一个人想项目分配从国外库添加到一个类的实例:Python的补丁项目分配

# defined outside our code base 
class WeDoNotWantToDeriveThis(object): pass 


inst = WeDoNotWantToDeriveThis() 
def set_item_func(self, idx, val): print("hi there") 
import types 
# try to patch item setter 
inst.__setitem__ = types.MethodType(set_item_func, inst) 
assert hasattr(inst, '__setitem__') 
print(type(inst.__setitem__)) # prints "instancemethod" 
# try to perform item assignment on inst 
inst[0] = None # raises 'object does not support item assignment' 

的问题是如何正确地做到这一点。也许'setitem'没有在实例上查找,但在类本身上检查对象是否支持项目分配?

根据该文件,执行setitem方法应该是足够了: https://docs.python.org/3/reference/datamodel.html#object.setitem

+0

尽量实现'__getitem__'代替。 –

+1

为什么不是子类而不是猴子修补? – jonrsharpe

+0

因为这将需要太多的代码更改。它现在应该是一个简单的解决方法。 – marscher

回答

1

必须设置在类的实例方法:

>>> WeDoNotWantToDeriveThis.__setitem__ = types.MethodType(set_item_func, None, WeDoNotWantToDeriveThis) 
>>> inst[0] = None 
hi there 
>>> 
+0

我真的必须修补实例(如果可能的话),因为我不想为该特定库的其他用户引入副作用。 – marscher

+1

不可能有副作用,因为项目分配仅供您使用。或者你重写默认的项目分配? –

+0

你的代码在Python3中引发了:TypeError:方法预期2个参数,得到3 – marscher