1. 程式人生 > 程式設計 >Python中的單下劃線和雙下劃線使用場景

Python中的單下劃線和雙下劃線使用場景

在這裡插入圖片描述

單下劃線

單下劃線用作變數

  • 最常見的一種使用場景是作為變數佔位符,使用場景明顯可以減少程式碼中多餘變數的使用。為了方便理解,_可以看作被丟棄的變數名稱,這樣做可以讓閱讀你程式碼的人知道,這是個不會被使用的變數,e.g.。
for _,_,filenames in os.walk(targetDir):
    print(filenames)
    
for _ in range(100):
    print('PythonPoint')
複製程式碼
  • 在互動直譯器比如iPython中,_變數指向互動直譯器中最後一次執行語句的返回結果。

單下劃線字首名稱(例如_pythonPoint)

  • 這表示這是一個保護成員(屬性或者方法),只有類物件和子類物件自己能訪問到這些變數,是用來指定私有變數和方法的一種方式(約定而已)。如果使用from a_module import *匯入時,這部分變數和函式不會被匯入。不過值得注意的是,如果使用import a_module這樣匯入模組,仍然可以用a_module._pythonPoint這樣的形式訪問到這樣的物件。

  • 另外單下劃線開頭還有一種一般不會用到的情況,例如使用一個C編寫的擴充套件庫有時會用下劃線開頭命名,然後使用一個去掉下劃線的Python模組進行包裝。如struct這個模組實際上是C模組_struct的一個Python包裝。

單下劃線字尾名稱

通常用於和Python關鍵詞區分開來,比如我們需要一個變數叫做class,但class是 Python的關鍵詞,就可以以單下劃線結尾寫作class_

雙下劃線

雙下劃線字首名稱

這表示這是一個私有成員(屬性或者方法)。它無法直接像公有成員一樣隨便訪問。雙下劃線開頭的命名形式在Python的類成員中使用表示名字改編,即如果Test類裡有一成員__x,那麼dir(Test)時會看到_Test__x而非__x。這是為了避免該成員的名稱與子類中的名稱衝突,方便父類和子類中該成員的區分識別。但要注意這要求該名稱末尾最多有一個下劃線。e.g.

在這裡插入圖片描述

雙下劃線字首及字尾名稱

一種約定,Python內部的名字,用來區別其他使用者自定義的命名,以防衝突。是一些Python的“魔術”物件,表示這是一個特殊成員。如類成員的__init__

__del____add__等,以及全域性的__file____name__ 等。Python官方推薦永遠不要將這樣的命名方式應用於自己的變數或函式,而是按照檔案說明來使用Python內建的這些特殊成員。


Python中關於私有屬性、方法約定問題,官方檔案如下

“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However,there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function,a method or a data member). It should be considered an implementation detail and subject to change without notice.

Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses),there is limited support for such a mechanism,called name mangling. Any identifier of the form__spam (at least two leading underscores,at most one trailing underscore) is textually replaced with _classname__spam,where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier,as long as it occurs within the definition of a class.

Name mangling is helpful for letting subclasses override methods without breaking intraclass method calls.

以上~


在這裡插入圖片描述