掘金 后端 ( ) • 2024-04-24 10:15

左手编程,右手年华。大家好,我是一点,关注我,带你走入编程的世界。

公众号:一点sir,关注Python领取编程资料

在Python中,下划线是一个多功能的字符,它在不同的上下文中扮演着不同的角色。Python社区通过使用下划线来约定一些特定的行为和模式,这些约定有助于提高代码的可读性和一致性。

单下划线开头(保护成员)

当一个变量或方法名称以单个下划线开头时,它被视为“受保护的”(protected),这是一种约定,表明这个成员不应该被公开访问,而是作为类的内部实现细节。

class MyClass:
   def __init__(self):
       self._internal_var = 10  # 受保护的成员变量

双下划线开头(名称改写)

如果一个成员名称以双下划线开头,Python将使用名称改写(也称为“命名冲突解决”)来解决可能的冲突。这会导致一个不同的名称被创建,通常是通过在原始名称前添加两个下划线和类名的方式。

class Parent:
   def __method(self):
       pass

class Child(Parent):
   def __method(self):
       pass

c = Child()
c._P_method()  # 正确,调用Parent的__method
c.__method()   # 错误,Python不允许直接访问

单下划线结尾(避免命名冲突)

当一个变量名以单个下划线结尾时,这通常用来避免与Python的关键字发生冲突。

class MyClass:
   def __init__(self):
       self.class_ = "Python"  # 避免与关键字class冲突

双下划线特殊方法

以双下划线开头和结尾的名称在Python中用于特殊方法,也称为魔术方法(如__init__, __str__, __call__等)。这些方法有特定的用途,并且当以特定方式调用时,Python解释器会自动使用它们。

class MyClass:
   def __init__(self):
       self.value = 1

   def __call__(self):
       print("Called as a function!")

obj = MyClass()
obj()  # 调用__call__方法,输出: Called as a function!

下划线开头的变量(从导入中忽略)

在模块级别,如果一个变量或函数名称以下划线开头,它们默认不会被from module import *语句导入。

# some_module.py
def _private_function():
   print("This won't be imported with *")

def public_function():
   print("This will be imported with *")

_private_var = "This won't be imported with *"
public_var = "This will be imported with *"

# other_script.py
from some_module import *

print(public_function())  # 正常工作
print(_private_function())  # 错误,_private_function未被导入

下划线在Python中的使用是社区约定的一部分,它帮助开发者理解特定变量或方法的预期用途。正确地使用下划线可以减少命名冲突,提高代码的清晰度,并且遵循Python的编码风格。