小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

兩分鐘掌握Python中下劃線 ‘_’ 用法

 禁忌石 2023-09-23

Python中下劃線()是一個有特殊含義和用途的符號,它可以用來表示以下幾種情況:

1 在解釋器中,下劃線(_)表示上一個表達式的值,可以用來進行快速計算或測試。

例如:

>>> 2 + 35>>> _5>>> _ * 210

2 在循環(huán)或解包中,下劃線(_)表示忽略某個值,可以用來省略不需要的變量。

  • 例如:
>>> for _ in range(3):...     print('Hello')...HelloHelloHello>>> x, _, y = (1, 2, 3)>>> x1>>> y3

3 在變量或函數(shù)名中,單下劃線開頭(_)表示這是一個內(nèi)部使用或受保護的名稱,不建議從外部訪問。這只是一種約定,不會影響實際的訪問權(quán)限。

  • 例如:
class Test: def _internal_method(self): # this method is for internal use only pass def public_method(self): # this method is for public use self._internal_method()

4 在變量或函數(shù)名中,單下劃線結(jié)尾(_)表示這是為了避免與Python關(guān)鍵字或內(nèi)置函數(shù)沖突而添加的后綴。

  • 例如:
def make_object(name, class_):    # use class_ instead of class to avoid conflict with keyword    passlist_ = list(range(10))# use list_ instead of list to avoid conflict with built-in function

5 在變量或函數(shù)名中,雙下劃線開頭(__)表示這是一個私有的名稱,只能在類內(nèi)部訪問。Python會對這種名稱進行名稱修飾(name mangling),即在名稱前面加上類名和一個下劃線,以防止子類中出現(xiàn)同名的屬性。

  • 例如:
class Test: def __init__(self): self.__private_var = 42 # this is a private variable def __private_method(self): # this is a private method passt = Test()print(t.__private_var) # AttributeError: 'Test' object has no attribute '__private_var'print(t._Test__private_var) # 42, this is the mangled name

6 在變量或函數(shù)名中,雙下劃線開頭和結(jié)尾(__)表示這是一個特殊的或魔法的名稱,通常與Python的語法或內(nèi)部機制有關(guān)。

  • 例如:
class Test:    def __init__(self, value):        # this is a special method for initializing an object        self.value = value    def __str__(self):        # this is a special method for converting an object to a string        return f'Test({self.value})'    def __add__(self, other):        # this is a special method for implementing the + operator        return Test(self.value + other.value)t1 = Test(10)t2 = Test(20)print(t1) # Test(10)print(t1 + t2) # Test(30)

7 在變量名中,單獨一個下劃線(_)表示這是一個臨時或無關(guān)緊要的變量,通常用于國際化(i18n)或本地化(l10n)功能。

  • 例如:
import gettext# use _ as a shorthand for gettext.gettext functiongettext.bindtextdomain('myapplication', '/path/to/my/language/directory')gettext.textdomain('myapplication')_ = gettext.gettext# use _() to mark the strings that need to be translatedprint(_('This is a translatable string.'))
兩分鐘掌握Python中下劃線

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多