_var
var_
__var
__var__
_
class Test: def __init__(self): self.foo = 11 self._bar = 23
>>> t = Test() >>> t.foo 11 >>> t._bar 23
class
或def
不能將其用做變量名稱。在這種狀況下,您能夠附加一個下劃線以消除命名衝突>>> def make_object(name, class): SyntaxError: "invalid syntax" >>> def make_object(name, class_): ... pass
讓咱們使用內置dir()
函數查看該對象的屬性:python
class Test: def __init__(self): self.foo = 11 self._bar = 23 self.__baz = 23
>>> dir(t) ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_bar', 'foo']
__baz
這是Python解釋程序應用的名稱修飾。這樣作是爲了防止變量在子類中被覆蓋。class ExtendedTest(Test): def __init__(self): super().__init__() self.foo = 'overridden' self._bar = 'overridden' self.__baz = 'overridden'
>>> t2 = ExtendedTest() >>> t2.foo 'overridden' >>> t2._bar 'overridden' >>> t2.__baz AttributeError: 'ExtendedTest' object has no attribute '__baz'
>>> dir(t2) ['_ExtendedTest__baz', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_bar', 'foo']
>>> t2._ExtendedTest__baz 'overridden'
>>> t2._Test__baz 23
class ManglingTest: def __init__(self): self.__mangled = 'hello' def get_mangled(self): return self.__mangled
>>> ManglingTest().get_mangled() 'hello' >>> ManglingTest().__mangled AttributeError: "'ManglingTest' object has no attribute '__mangled'"
class MangledMethod: def __method(self): return 42 def call_it(self): return self.__method()
>>> MangledMethod().__method() AttributeError: "'MangledMethod' object has no attribute '__method'" >>> MangledMethod().call_it() 42
_MangledGlobal__mangled = 23 class MangledGlobal: def test(self): return __mangled
>>> MangledGlobal().test() 23
_MangledGlobal__mangled
。而後,我在名爲的類的上下文中訪問了變量MangledGlobal
。因爲名稱修改,我可以_MangledGlobal__mangled
像在類上的方法__mangled
內部同樣引用全局變量test()
。__mangled
,_MangledGlobal__mangled
由於它以兩個下劃線字符開頭。這代表名稱修飾與類屬性無關。它適用於任何以類上下文中使用的兩個下劃線字符開頭的名稱。__init__
了對象構造函數或__call__
使對象可調用之類的內容。這些dunder方法一般被稱爲魔術方法class PrefixPostfixTest: def __init__(self): self.__bam__ = 42
>>> PrefixPostfixTest().__bam__ 42
>>> for _ in range(3): print("Python") Python Python Python
car
元組拆成單獨的變量,可是我只對color
and的值感興趣mileage
。可是,爲了使解包表達式成功,我須要將元組中包含的全部值分配給變量。那是「 _
」用做佔位符變量的地方>>> car = ('red', 'auto', 12, 3812.4) >>> color, _, _, mileage = car >>> color 'red' >>> mileage 3812.4 >>> _ 12
_
」仍是大多數Python REPL中的特殊變量,它表明解釋器評估的最後一個表達式的結果。若是您在解釋器會話中工做,而且想訪問之前的計算結果,這將很方便。或者,若是您正在動態構建對象,而且想與它們交互而不先給它們指定名稱,則:>>> 20 + 3 23 >>> _ 23 >>> print(_) 23 >>> list() [] >>> _.append(1) >>> _.append(2) >>> _.append(3) >>> _ [1, 2, 3]
Pattern | Example | Meaning |
---|---|---|
Single Leading Underscore | _var |
Naming convention indicating a name is meant for internal use. Generally not enforced by the Python interpreter (except in wildcard imports) and meant as a hint to the programmer only. |
Single Trailing Underscore | var_ |
Used by convention to avoid naming conflicts with Python keywords. |
Double Leading Underscore | __var |
Triggers name mangling when used in a class context. Enforced by the Python interpreter. |
Double Leading and Trailing Underscore | __var__ |
Indicates special methods defined by the Python language. Avoid this naming scheme for your own attributes. |
Single Underscore | _ |
Sometimes used as a name for temporary or insignificant variables (「don’t care」). Also: The result of the last expression in a Python REPL. |
模式 | 例 | 含義 |
---|---|---|
Single Leading Underscore | _var |
表示名稱的命名約定僅供內部使用。一般不禁Python解釋器強制執行(通配符導入除外),而且僅做爲對程序員的提示。 |
Single Trailing Underscore | var_ |
按照慣例使用,以免與Python關鍵字命名衝突。 |
Double Leading Underscore | __var |
在類上下文中使用時觸發名稱修改。由Python解釋器強制執行。 |
Double Leading and Trailing Underscore | __var__ |
表示由Python語言定義的特殊方法。避免爲您本身的屬性使用此命名方案。 |
Single Underscore | _ |
有時用做臨時變量或可有可無變量的名稱(「可有可無」)。另外:Python REPL中最後一個表達式的結果。 |
原文:https://dbader.org/blog/meaning-of-underscores-in-python程序員