_
能夠看做被丟棄的變量名稱,這樣作可讓閱讀你代碼的人知道,這是個不會被使用的變量,e.g.。for _, _, filenames in os.walk(targetDir): print(filenames) for _ in range(100): print('PythonPoint')
_
變量指向交互解釋器中最後一次執行語句的返回結果。from a_module import *
導入時,這部分變量和函數不會被導入。不過值得注意的是,若是使用import a_module
這樣導入模塊,仍然能夠用a_module._pythonPoint
這樣的形式訪問到這樣的對象。_struct
的一個Python包裝。class_
。這表示這是一個私有成員(屬性或者方法)。它沒法直接像公有成員同樣隨便訪問。雙下劃線開頭的命名形式在Python的類成員中使用表示名字改編,即若是Test類裏有一成員__x
,那麼dir(Test)
時會看到_Test__x
而非__x
。這是爲了不該成員的名稱與子類中的名稱衝突,方便父類和子類中該成員的區分識別。但要注意這要求該名稱末尾最多有一個下劃線。e.g.python
一種約定,Python內部的名字,用來區別其餘用戶自定義的命名,以防衝突。是一些Python的「魔術」對象,表示這是一個特殊成員。如類成員的__init__
、__del__
、__add__
等,以及全局的__file__
、__name__
等。Python官方推薦永遠不要將這樣的命名方式應用於本身的變量或函數,而是按照文檔說明來使用Python內置的這些特殊成員。ide
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.spa
Name mangling is helpful for letting subclasses override methods without breaking intraclass method calls.3d