Python中的下划线到底什么意思?
1. 概述
在Python經常能見到含下劃線(underscore)修飾的的變量和方法(如__name__,_var等),這些下劃線的作用稱之為名字修飾(name decoration)。在Python中,名字修飾通常有以下幾種情況:
- 單前綴下劃線(single leading underscore):_var
- 單后綴下劃線(single trailingunderscore):var_
- 雙前綴下劃線(double leading underscores):__var
- 雙前綴+雙后綴下劃線(double leading & trailing underscores):__var__
除了名字修飾,在Python中下劃線還有以下用法:
- 單獨一個下劃線
- 數字分隔符下劃線
- IPython中的特殊用途
我們對以上用法進行逐一詳解。
2. 名字修飾(name decoration)
2.1 單前綴下劃線
方法和實例變量
Use one leading underscore only for non-public methods and instance variables.[1]即,單前綴下劃線用于私有的方法和實例變量。但Python和Java不同,并沒有對公有和私有進行嚴格的區分。即便一個方法或者變量有單前綴下劃線,也不影響被外界調用,它的作用僅限于一種“提示”(weak “internal use” indicator)。
class Test:def __init__(self):self.a = "a"self._b = "b"def _private_method(self):return ("This is a private method!")# 單前綴下劃線并不影響從外界調用 t = Test() print(t.a) print(t._b) print(t._private_method)導入
from M import *does not import objects whose names start with an underscore.[1]即,當從另一個模塊導入內容是,含前綴下劃線的內容不會被導入。如
# demo.py a = "a" _b = "b"def _private_function():return "This is a private function!" from demo import *print(a) print(_b) # 會報錯,私有變量無法導入 print(_private_function) # 會報錯,私有函數無法導入2.2 單后綴下劃線
single_trailing_underscore_: used by convention to avoid conflicts with Python keyword[1]單后綴下劃線主要是為了避免與一些Python關鍵字(如class,sum之類的)的沖突,如
tkinter.Toplevel(master, class_='ClassName')2.3 雙前綴下劃線
To avoid name clashes with subclasses, use two leading underscores to invoke Python's name mangling rules.Python mangles these names with the class name: if class Foo has an attribute named?__a, it cannot be accessed by?Foo.__a. (An insistent user could still gain access by calling?Foo._Foo__a.) Generally, double leading underscores should be used only to avoid name conflicts with attributes in classes designed to be subclassed.[1]
雙前綴下劃線會觸發Python中的名字改寫規則(name mangling)什么意思呢?舉個例子
class Test:__a = "__a"def __init__(self) -> None:self.__b = "__b"self._c = "_c"self.d = "d"t = Test() print(dir(t))猜猜會打印什么呢?結果如下
name mangling
你會發現有_c和d,但是沒有__a和__b。這是為什么呢?這是因為他們被改寫成了_Test__a和_Test_b。因為名字被改寫,所以不能通過t.__a訪問,但是可以通過t._Test__a進行訪問。
print(t.__a) # 會報錯 print(t._Test__a) # 不會報錯為什么要這樣設計呢?這樣是為了避免在繼承的時候,這些變量被重寫,如
class Test:__a = "__a"class SubTest(Test):__a = "change __a"st = SubTest() print(dir(st))執行結果如下,如果在子類中重新定義__a時,會重新生成一個_SubTest__a,這樣避免了父類中的_Test__a被改寫。
除了_Test__a,還有_SubTest__a
2.4 雙前綴+雙后綴下劃線
與雙前綴下劃線不同,雙前綴+雙后綴下劃線并不會對名字進行改寫。這些使用了雙前綴+雙后綴下劃線的對象又被稱為dunders,即Double UNDERScores的縮寫。
魔法函數
__double_leading_and_trailing_underscore__: “magic” objects or attributes that live in user-controlled namespaces. E.g.?__init__,?__import__?or?__file__. Never invent such names; only use them as documented.雙前綴+雙后綴下劃線常用于“魔法函數”,表明這些函數被“官方占用”,不建議自行定義一個雙前綴+雙后綴下劃線的對象,因為有可能與“官方用法”產生沖突。
模塊
Module level “dunders” (i.e. names with two leading and two trailing underscores) such as__all__,__author__,__version__, etc. should be placed after the module docstring but before any import statements?exceptfrom__future__imports. Python mandates that future-imports must appear in the module before any other code except docstrings:除了魔法函數,一些模塊也使用了雙前綴+雙后綴下劃線,如__future__。Python要求的導入順序是:__future__的import放在最前,然后是dunders的import,最后是普通的import。其中__future__的import強制放在最前,否則會報錯。
""" This is a demo! 這種docstrings放在最前 """from __future__ import barry_as_FLUFL__all__ = ["test"] __version__ = '0.1' __author__ = 'Mr. Cheng'import pandas as pd3. 其他用法
3.1 單獨一個下劃線
當我們需要一個變量,但是又不需要在后面的程序中調用這個變量時,就可以用_,相當于告訴大家:這個變量無關緊要。最典型的例子就是用于for循環,如
for _ in range(10):print("打印10次!")也可以用作占位符對可迭代對象進行拆分,如
a, _, _, c = (1, 2, 3, 4) a, _, _, c = [1, 2, 3, 4]3.2 數字分隔符
在會計中,我們用逗號對較大的數字進行分隔,以方便識別,如93,123,110。但是在Python中,顯然不能用逗號,但是可以用下劃線,如:
a = 93_123_1103.3 IPython中的特殊用途
在iPython中,下劃線還有一個特殊用途:用以指代最近一個表達式的輸出結果。如
在學編程,學Python的小伙伴們,一個人摸黑學會很難,博主也是過來人, 這里新建了一個扣群:1020465983,給大家準備了學習資源、好玩的項目,歡迎大家加入一起交流。
總結
以上是生活随笔為你收集整理的Python中的下划线到底什么意思?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 凸多边形面积
- 下一篇: 网页背景动态线条 鼠标吸附动态线条效果的