代码之家  ›  专栏  ›  技术社区  ›  James Hopkin

正在将\uuu getitem\转发到getattr

  •  3
  • James Hopkin  · 技术社区  · 14 年前

    class Test(object):
        __getitem__ = getattr
    
    t = Test()
    t['foo']
    

    给出错误(在Python2.7和3.1中):

    TypeError: getattr expected at least 2 arguments, got 1
    

    def f(*params):
         print params    # or print(params) in 3.1
    
    class Test(object):
        __getitem__ = f
    

    打印我期望的两个参数。

    2 回复  |  直到 14 年前
        1
  •  6
  •   user79758 user79758    14 年前

    令人困惑的是,当在类中使用时,内置函数(以及某些其他类型的可调用函数)不会像普通函数那样成为绑定方法:

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

    与之相比:

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

    因此,getattr没有正确接收第一个('self')参数。您需要编写一个普通方法来包装它。

        2
  •  0
  •   Chris R    14 年前

    您想这样做:

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