Forwarding __getitem__ to getattr

Can someone explain what is going on here?

class Test(object):
    __getitem__ = getattr

t = Test()
t['foo']

gives an error (in Python 2.7 and 3.1):

TypeError: getattr expected at least 2 arguments, got 1

then:

def f(*params):
     print params    # or print(params) in 3.1

class Test(object):
    __getitem__ = f

prints two parameters that I would expect.

+3
source share
2 answers

Vaguely, built-in functions (and some other types of calls) do not become related methods, since ordinary functions are executed when used in a class:

>>> class Foo(object): __getitem__ = getattr
>>> Foo().__getitem__
<built-in function getattr>

Compared with:

>>> def ga(*args): return getattr(*args)
>>> class Foo(object): __getitem__ = ga
>>> Foo().__getitem__
<bound method Foo.ga of <__main__.Foo object at 0xb77ad94c>>

So getattr gets the first ("self") parameter incorrectly. You will need to write a regular method to port it.

+6
source

getattr is called without the "self" parameter, because it is assigned an object property.

You want to do this:

__getitem__ = lambda *a, **k: getattr(*a, **k)

This will give you the result that you think is necessary.

0
source

Source: https://habr.com/ru/post/1764502/


All Articles