Python 下划线

  • 单个前导下划线:

    用于表示该变量是模块内部使用的,作为约定,告诉其他开发者这不是公共接口的一部分,不建议直接访问

    1
    2
    3
    4
    5
    6
    class MyClass:
    def __init__(self):
    self.public_variable = 42
    self._protected_variable = 'protected data'
    obj = MyClass()
    print(obj._protected_variable) # 输出: protected data
  • 单个末尾下划线

    避免与Python关键字或者内置函数名命名冲突时,可以使用单个末尾下划线来重命名变量,如class_可以避免与class冲突

    class_ = 'test'
    print(class_)  # 输出: test
    ------------------------------
    class= 'test'
        File "<stdin>", line 1
          class= 'test'
             ^
    SyntaxError: invalid syntax
  • 双前导下划线

    名称修饰,保护父类属性的访问,防止子类属性覆盖父类属性,访问方法obj._类名__属性名

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    class Parent:
    def __init__(self):
    self.__x = 10 # 使用双前导下划线命名属性

    class Child(Parent):
    def __init__(self):
    super().__init__()
    self.__x = 20 # 子类定义相同名称的属性

    parent = Parent()
    child = Child()

    print(parent.__dict__) # 输出 {'_Parent__x': 10}
    print(child.__dict__) # 输出 {'_Parent__x': 10, '_Child__x': 20}

    print(parent._Parent__x) # 输出 10
    print(child._Child__x) # 输出 20

  • 双前导和双末尾下划线

    用于标识特殊方法(魔术方法),如 __init__(构造方法)、__str__(字符串表示方法)。

    预定义的特殊名称,如,__name__ 是一个包含当前模块名称的特殊变量。__file__ 包含当前模块的文件路径。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    class MyClass:
    def __init__(self):
    self.__count__ = 0

    def __str__(self):
    return f"MyClass instance with count: {self.__count__}"
    if __name__ =='__main__': # 预定义的特殊名称
    obj = MyClass()
    obj.__count__ = 5 # 使用末尾下划线的特殊变量
    print(obj) # 输出 "MyClass instance with count: 5"

  • 单个下划线:

    用来表示无关紧要的变量

    1
    2
    for _ in range(5):
    print('test')

    在交互式解释器中,_指向最后一次执行的表达式结果

    1
    2
    3
    4+8
    7+9
    _ # 输出16

:D 一言句子获取中...