python - 是否可以在 Python 的实例级别覆盖 __getitem__?

标签 python monkeypatching

使用以下代码:

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/

相关文章:

python - Pyplot 饼图错误,值较小

python - Django 管理,通过 ManyToMany 引用过滤对象

python - 如何理解和解析默认的 Python 对象表示

python - 显示上传的文件django

python - 猴子在 python 中修补 time.time()

python - 升级urllib3导致cloud-init失败,显然urllib3和python请求存在版本兼容性问题?

ruby-on-rails-3 - 猴子补丁模块方法

python - Monkey 使用类中的原始方法修补 python 实例方法

python - 修补本地实例

.net - PowerShell,扩展方法和猴子修补