2010-10-06 97 views
12

在Python中,我写了这个:这为什么会导致语法错误?

bvar=mht.get_value() 
temp=self.treemodel.insert(iter,0,(mht,False,*bvar)) 

我试图扩大BVAR的函数调用作为参数。 但它然后返回,

File "./unobsoluttreemodel.py", line 65 
    temp=self.treemodel.insert(iter,0,(mht,False,*bvar)) 
               ^
SyntaxError: invalid syntax 

什么刚刚发生?它应该是正确的吗?

回答

21

如果你想传递的最后一个参数为(mnt, False, bvar[0], bvar[1], ...)一个元组,你可以使用

temp = self.treemodel.insert(iter, 0, (mht,False)+tuple(bvar)) 

扩展调用语法*b只能在calling functionsfunction arguments在Python 3中使用,并且tuple unpacking。 X。

>>> def f(a, b, *c): print(a, b, c) 
... 
>>> x, *y = range(6) 
>>> f(*y) 
1 2 (3, 4, 5) 

元组文字不在这些情况之一,所以它会导致语法错误。

>>> (1, *y) 
    File "<stdin>", line 1 
SyntaxError: can use starred expression only as assignment target 
+1

对,'*'分辨率操作符不允许创建元组。 – AndiDog 2010-10-06 08:51:11

0

您似乎在那里有一个额外的括号。尝试:

temp=self.treemodel.insert(iter,0,mht,False,*bvar) 

你额外的括号正试图创建一个使用*语法,这是一个语法错误的元组。

2

不是这样。参数扩展只能在函数参数中使用,不能在元组中使用。

>>> def foo(a, b, c): 
...  print a, b, c 
... 
>>> data = (1, 2, 3) 
>>> foo(*data) 
1 2 3 

>>> foo((*data,)) 
    File "<stdin>", line 1 
    foo((*data,)) 
     ^
SyntaxError: invalid syntax 
28

更新:这种行为已被固定在Python 3.5.0,请参阅PEP-0448

开箱建议被允许里面的元组,列表,设置和字典显示:

*range(4), 4 
# (0, 1, 2, 3, 4) 

[*range(4), 4] 
# [0, 1, 2, 3, 4] 

{*range(4), 4} 
# {0, 1, 2, 3, 4} 

{'x': 1, **{'y': 2}} 
# {'x': 1, 'y': 2} 
相关问题