开发者

Forwarding __getitem__ to getattr

Can someone explain what is happening here?

class Test(object):
    __getitem__ = getattr

t = Test()
t['foo']

gives error (in Python 2.7 and 3.1):

TypeError: getattr expected at least 2 arguments, got 1

whereas:

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

class Test(object):
    __getitem__ = f

prints the two parameters I'd e开发者_StackOverflow社区xpect.


Confusingly, built-in functions (and certain other types of callables) do not become bound methods as normal functions do when used in a class:

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

Compared to:

>>> 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 is not correctly receiving the first ('self') parameter. You'll need to write a normal method to wrap it.


getattr is being called without the 'self' parameter because it's assigned to an object property.

You want to do this:

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

That will give you the output you seem to want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜