2013-11-28 62 views
1

大家好,我的問題顯而易見,我就像是一個全新的python。 我很困惑,當我閱讀蟒蛇,甚至在這裏的論壇#1的文件...Python中的下劃線是什麼意思

他們爲什麼寫這樣的

from __future__ import division 

什麼是圍繞未來字下劃線是什麼意思? ?我們是否應該像python解釋器中的下劃線一樣使用它? 這只是衆多例子中的一個。任何幫助都會大大受到影響。

+1

我猜他們使用了特殊的命名約定來避免衝突。不要反套。你應該完全按照它的寫法來使用它。 – keyser

+1

我打算用另一個答案來回答這個問題:http://stackoverflow.com/a/3443428/1707253 – turnt

+0

這已經回答過。 http://stackoverflow.com/q/15090825/165103 –

回答

3

根據PEP 236建議使用該模塊,雙下劃線使其成爲保留名稱。

[5] This ensures that a future_statement run under a release prior to 
    the first one in which a given feature is known (but >= 2.1) will 
    raise a compile-time error rather than silently do a wrong thing. 
    If transported to a release prior to 2.1, a runtime error will be 
    raised because of the failure to import __future__ (no such module 
    existed in the standard distribution before the 2.1 release, and 
    the double underscores make it a reserved name). 
0

名稱開始和以雙下劃線結束(如__foo__)在Python special names(其中大多數是對對象的方法,__future__恰好是一個模塊)。它們的特殊之處在於Python對它們賦予了一些特殊的含義,並且它們被保留用於此目的。

你確實應該這樣寫。

這不同於只有像__foo這樣的前兩個下劃線的名稱 - 這些名稱受制於name mangling,它們可以用於創建類別專用屬性。

相關問題