[英]Using keyword arguments in __getitem__ method in Python
我想定義一個類Foo,其對象可以像foo[1, a=2]
。
我試圖通過裝飾Foo的__getitem__
方法來實現這一點,但沒有成功。 下面是示例代碼。
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)
。
使用關鍵字參數進行索引當前是語法錯誤。
但是,PEP472( https://www.python.org/dev/peps/pep-0472/ )建議添加python語法。
PEP還顯示了當前有效的變通方法:
foo[2, "a":10]
或foo[2, {"a":10}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.