李成笔记网

专注域名、站长SEO知识分享与实战技巧

Python中下划线 ‘_’ 的用法,你知道几种

Python中下划线()是一个有特殊含义和用途的符号,它可以用来表示以下几种情况:

1 在解释器中,下划线(_)表示上一个表达式的值,可以用来进行快速计算或测试。

例如:

>>> 2 + 3
5
>>> _
5
>>> _ * 2
10

2 在循环或解包中,下划线(_)表示忽略某个值,可以用来省略不需要的变量。

  • 例如:
>>> for _ in range(3):
...     print("Hello")
...
Hello
Hello
Hello

>>> x, _, y = (1, 2, 3)
>>> x
1
>>> y
3

3 在变量或函数名中,单下划线开头(_)表示这是一个内部使用或受保护的名称,不建议从外部访问。这只是一种约定,不会影响实际的访问权限。

  • 例如:
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 在变量或函数名中,单下划线结尾(_)表示这是为了避免与Python关键字或内置函数冲突而添加的后缀。

  • 例如:
def make_object(name, class_):
    # use class_ instead of class to avoid conflict with keyword
    pass

list_ = list(range(10))
# use list_ instead of list to avoid conflict with built-in function

5 在变量或函数名中,双下划线开头(__)表示这是一个私有的名称,只能在类内部访问。Python会对这种名称进行名称修饰(name mangling),即在名称前面加上类名和一个下划线,以防止子类中出现同名的属性。

  • 例如:
class Test:
    def __init__(self):
        self.__private_var = 42 # this is a private variable

    def __private_method(self):
        # this is a private method
        pass

t = 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 在变量或函数名中,双下划线开头和结尾(__)表示这是一个特殊的或魔法的名称,通常与Python的语法或内部机制有关。

  • 例如:
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 在变量名中,单独一个下划线(_)表示这是一个临时或无关紧要的变量,通常用于国际化(i18n)或本地化(l10n)功能。

  • 例如:
import gettext

# use _ as a shorthand for gettext.gettext function
gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')
gettext.textdomain('myapplication')
_ = gettext.gettext

# use _() to mark the strings that need to be translated
print(_('This is a translatable string.'))

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言