使用以下代码:
import types
class Foo():
def __getitem__(self, x):
return x
def new_get(self, x):
return x + 1
x = Foo()
x.__getitem__ = types.MethodType(new_get, x)
x.__getitem__(42)
将返回 43,但 x[42]
将返回 42。
有没有办法在 Python 的实例级别覆盖 __getitem__
?
最佳答案
不幸的是,这是不允许的:
For custom classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary.
来源:https://docs.python.org/3/reference/datamodel.html#special-lookup
关于python - 是否可以在 Python 的实例级别覆盖 __getitem__?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57413453/