2010-10-06 76 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}