假设有人想将项目分配添加到外部库中的类实例:
# 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