下劃線在 Python 中有很特別的意義。
開門見山
下劃線在 Python 中有特殊的意義,簡單來說,可以總結成三點。
- 單下劃線在前一般用于聲明私有成員,比如 _private_var
- 單下劃線在后一般用于命名已經(jīng)被保留關鍵字占用的變量,比如 class_,type_
- 雙下劃線一般被用于 Python 內置的特殊方法或者屬性,比如 __name__,__file__,有時候也被稱之為魔方方法。
更多細節(jié)的討論,可以看 StackOverflow 上的這個主題:What is the meaning of single and double underscore before an object name?[1]。
__foo__: this is just a convention, a way for the Python system to use names that won't conflict with user names.
_foo: this is just a convention, a way for the programmer to indicate that the variable is private (whatever that means in Python).
__foo: this has real meaning: the interpreter replaces this name with _classname__foo as a way to ensure that the name will not overlap with a similar name in another class.
No other form of underscores have meaning in the Python world.
There's no difference between class, variable, global, etc in these conventions.
有時候我們還能看到就僅僅命名為一個下劃線的的變量,這種情況一般是這個變量不重要或者只是一個臨時工,連名字都不配擁有。
- for _,value in func(): # 假如func每次會返回兩個值,我們只關心第二個值
- use(value)
思維導圖
下面是思維導圖的總結
如何調用魔法方法
一些魔法方法直接和內建函數(shù)對應,這種情況下,如何調用它們是顯而易見的。這有個附錄可以作為調用魔法方法的參考。
魔法方法 | 什么時候被調用 | 解釋 |
---|---|---|
__new__(cls [,...]) |
instance = MyClass(arg1, arg2) |
__new__ 在實例創(chuàng)建時調用 |
__init__(self [,...]) |
instance = MyClass(arg1,arg2) |
__init__ 在實例創(chuàng)建時調用 |
__cmp__(self) |
self == other , self > other 等 |
進行比較時調用 |
__pos__(self) |
self |
一元加法符號 |
__neg__(self) |
-self |
一元減法符號 |
__invert__(self) |
~self |
按位取反 |
__index__(self) |
x[self] |
當對象用于索引時 |
__nonzero__(self) |
bool(self) |
對象的布爾值 |
__getattr__(self, name) |
self.name #name 不存在 |
訪問不存在的屬性 |
__setattr__(self, name) |
self.name = val |
給屬性賦值 |
__delattr__(self, name) |
del self.name |
刪除屬性 |
__getattribute__(self,name) |
self.name |
訪問任意屬性 |
__getitem__(self, key) |
self[key] |
使用索引訪問某個元素 |
__setitem__(self, key) |
self[key] = val |
使用索引給某個元素賦值 |
__delitem__(self, key) |
del self[key] |
使用索引刪除某個對象 |
__iter__(self) |
for x in self |
迭代 |
__contains__(self, value) |
value in self, value not in self |
使用 in 進行成員測試 |
__call__(self [,...]) |
self(args) |
“調用” 一個實例 |
__enter__(self) |
with self as x: |
with 聲明的上下文管理器 |
__exit__(self, exc, val, trace) |
with self as x: |
with 聲明的上下文管理器 |
__getstate__(self) |
pickle.dump(pkl_file, self) |
Pickling |
__setstate__(self) |
data = pickle.load(pkl_file) |
Pickling |
如果你還想了解關于魔方方法的更多細節(jié),那么你一定不能錯過:
- 魔法方法指南 [2]
- Magic method guide[3]
參考資料
[1]What is the meaning of single and double underscore before an object name?: http://stackoverflow.com/questions/1301346/the-meaning-of-a-single-and-a-double-underscore-before-an-object-name-in-python
[2]魔法方法指南: http://pyzh.readthedocs.io/en/latest/python-magic-methods-guide.html
[3]Magic method guide: http://www.rafekettler.com/magicmethods.html
原文鏈接:https://mp.weixin.qq.com/s/gZzuZOKoI-NOdnKOKbQESQ