[英]Python: What do double parenthesis do?
誰能告訴我為什么括號加倍?
self.__items.append((module, item))
內括號創建一個元組 。
>>> type(('a', 'b'))
<type 'tuple'>
從技術上講,可以創建沒有括號的元組:
>>> 'a', 'b'
('a', 'b')
但有時他們需要括號:
>>> 'a', 'b' + 'c', 'd'
('a', 'bc', 'd')
>>> ('a', 'b') + ('c', 'd')
('a', 'b', 'c', 'd')
在您的情況下,他們需要括號來區分元組和逗號分隔的參數到函數。 例如:
>>> def takes_one_arg(x):
... return x
...
>>> takes_one_arg('a', 'b')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: takes_one_arg() takes exactly 1 argument (2 given)
>>> takes_one_arg(('a', 'b'))
('a', 'b')
它將元組(module, item)
作為單個參數傳遞給函數。 如果沒有額外的parens,它會將module
和item
作為單獨的參數傳遞。
這跟說:
parameter = (module, item)
self.__items.append(parameter)
也就是說,在將元組用作append()
的單個參數之前,內部的parens首先創建一個元組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.