Is it possible to override __getitem__ at instance level in Python?

后端 未结 2 1888
一个人的身影
一个人的身影 2021-02-13 23:25

With the following code :

import types

class Foo():
    def __getitem__(self, x):
        return x

def new_get(self, x):
    return x + 1

x = Foo()
x.__getite         


        
2条回答
  •  感情败类
    2021-02-13 23:58

    This is unfortunately, and quite surprisingly, not allowed:

    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.

    Source: https://docs.python.org/3/reference/datamodel.html#special-lookup

提交回复
热议问题