在Python中的__getitem__方法中使用关键字参数

Tim*_*ima 3 python metaprogramming

我想定义一个类Foo,其对象可以像,foo[1, a=2].

我试图通过装饰__getitem__Foo 的方法来实现这一点,但没有成功.下面是示例代码.

def decorator(func):
    def func_(*args, **kewargs):
        if 'a' in kewargs:
            args = list(args) + [kewargs['a']]
            return func(*args)
        else:
            return func(*args)
    return func_

class Foo(object):
    @decorator
    def __getitem__(self, *items):
        return items
foo = Foo()

>>> foo.__getitem__(2, a=10)
(2, 10)
>>> foo[2, a=10]
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

所以foo[...]不等同于foo.__getitem__(...),前者背后的东西是为前者完成的.我的问题是foo[2, a=10],如果有的话,我究竟能做什么以及如何工作.

vau*_*tah 6

Python允许隐式元组创建(没有括号):

In [2]: tup = 1, 2, 3

In [3]: tup
Out[3]: (1, 2, 3)
Run Code Online (Sandbox Code Playgroud)

它在方括号内的工作方式相同:

In [4]: d = {(1, 2, 3): 4}

In [5]: d[1, 2, 3]
Out[5]: 4
Run Code Online (Sandbox Code Playgroud)

(2, a=10)不是有效的元组文字:

In [6]: (2, a=10)
  File "<ipython-input-1-7dc03602f595>", line 1
    (2, a=10)
         ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

简单地说,你无法foo[2, a=10]工作,因为无论你如何调整你的__getitem__实现,它都是语法错误.

我可能会定义一个普通的方法,例如get并使用它Foo.get(2, a=10).