有人能告诉我为什么这里的括号是双倍的吗?
self.__items.append((module, item))
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)
作为单个参数传递给函数。如果没有额外的括号,它将把 module
和 item
分别作为参数传递。
这与说:
parameter = (module, item)
self.__items.append(parameter)
append()
。