2016-08-18 54 views
0

這段代碼爲什麼會這樣工作?爲什麼del(x)在變量名稱周圍帶括號?

x = 3 
print(dir()) #output indicates that x is defined in the global scope 
del (x) 
print(dir()) #output indicates that x is not defined in the global scope 

我的理解是,del是一個Python關鍵字,而接下來del應該是一個名字。 (name)不是一個名字。爲什麼該示例似乎顯示del (name)del name的作用相同?

+1

接下來'del'並不總是一個名字;考慮'del arr [n]'或'del obj.attr'。 – trentcl

+2

您可以在任何表達式周圍放置括號,並且該值與表達式相同。例如。 'foo = x'或'foo =(x)'是同樣的事情。 – Barmar

+0

'del(name)'被解釋爲'del(name)',並且括號被忽略。這就像在Python2.7中執行'print('name')',它被_interpreted_作爲'print('name')'。 –

回答

2

del statemant的定義是:

del_stmt :: = 「DEL」 target_list

並從target_list定義:

target_list :: =目標( 「,」target)* [「,」]
target :: =標識符 | 「(」target_list「)」| 「[」[target_list]「]」 | ...

您可以看到圍繞目標列表的括號是允許的。

例如,如果你定義x,y = 1,2所有這些都是允許的,並且具有相同的影響:

del x,y, 
del (x,y) 
del (x),[y] 
del [x,(y)] 
del ([x], (y)) 
相關問題