我想定义一个 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
所以 foo[...]
不等同于 foo.__getitem__(...)
,有些东西
幕后是为前者做的。我的问题是究竟是什么以及如何
我能让 foo[2, a=10]
正常工作吗?
最佳答案
Python 允许隐式创建元组(不带括号):
In [2]: tup = 1, 2, 3
In [3]: tup
Out[3]: (1, 2, 3)
在方括号内也是一样的:
In [4]: d = {(1, 2, 3): 4}
In [5]: d[1, 2, 3]
Out[5]: 4
但是 (2, a=10)
不是有效的元组文字:
In [6]: (2, a=10)
File "<ipython-input-1-7dc03602f595>", line 1
(2, a=10)
^
SyntaxError: invalid syntax
简而言之,您无法使 foo[2, a=10]
正常工作,因为无论您如何调整 __getitem__
实现,它都是一个语法错误。
我可能会定义一个普通的方法,例如get
并像 Foo.get(2, a=10)
一样使用它。
关于python - 在 Python 的 __getitem__ 方法中使用关键字参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31916617/