比方说,一个人想项目分配从国外库添加到一个类的实例: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
尽量实现'__getitem__'代替。 –
为什么不是子类而不是猴子修补? – jonrsharpe
因为这将需要太多的代码更改。它现在应该是一个简单的解决方法。 – marscher