[英]The `[]` operator more than syntactic sugar?
slice
對象最常見的語法似乎是int:int:int
,特別是在tuple
s list
s 和str
s 的[]
運算符中。 為什么這種語法不能用於實例化slice
是有道理的,
Python 3.10.4 (main, Jun 29 2022, 12:14:53) [GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 0:-1:1
File "<stdin>", line 1
0:-1:1
^
SyntaxError: illegal target for annotation
但是當測試查看slice
object 被隱式處理的位置時,結果是在[]
運算符中:
>>> [].__getitem__(0:-1:1)
File "<stdin>", line 1
[].__getitem__(0:-1:1)
^
SyntaxError: invalid syntax
>>> [][0:-1:1]
[]
>>> "".__getitem__(0:-1:1)
File "<stdin>", line 1
"".__getitem__(0:-1:1)
^
SyntaxError: invalid synta
>>> ""[0:-1:1]
''
這似乎與[]
是語法糖的常見解釋相沖突。 []
的幕后發生了什么?
[]
運算符創建一個slice
object 並將其傳遞給__getitem__
:
>>> [1, 2, 3][0:-1:1]
[1, 2]
>>> [1, 2, 3].__getitem__(slice(0, -1, 1))
[1, 2]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.