作为Python开发者,下划线(_
)可能是我们每天都会遇到的符号,但它却有着多种不同的含义和应用场景。本文将全面剖析Python中下划线的各种用法。
在Python中,单下划线常用作临时变量名,表示该变量不重要或将被忽略:
# 忽略不需要的返回值
for _ in range(10):
print("Hello")
# 解包时忽略某些值
x, _, z = (1, 2, 3) # 忽略第二个值
在gettext模块中,_
常用作翻译函数的别名:
import gettext
gettext.bindtextdomain('myapp', '/path/to/locale')
gettext.textdomain('myapp')
_ = gettext.gettext
print(_('Hello World')) # 根据locale返回翻译后的字符串
在Python REPL中,_
保存最后一次表达式的结果:
>>> 3 + 4
7
>>> _ + 2
9
以单下划线开头的变量或方法表示"protected"成员,这是一种命名约定而非强制限制:
class MyClass:
def __init__(self):
self.public = 10
self._protected = 20 # 提示这是内部使用
def public_method(self):
return self._protected
def _protected_method(self): # 提示子类可以覆盖
return self.public
注意:
from module import *
不会导入以_
开头的名称当变量名与Python关键字冲突时,可以添加下划线后缀:
class_ = "Python Class" # 避免与class关键字冲突
type_ = "example" # 避免与type内置函数冲突
双下划线前缀会导致Python解释器对名称进行改写,主要用于避免子类中的命名冲突:
class MyClass:
def __init__(self):
self.__private = 30 # 会被改写为_MyClass__private
def __private_method(self): # 会被改写为_MyClass__private_method
return self.__private
class SubClass(MyClass):
def __init__(self):
super().__init__()
self.__private = 40 # 会被改写为_SubClass__private
实际访问方式:
obj = MyClass()
print(obj._MyClass__private) # 可以这样访问,但不推荐
前后都有双下划线的方法是Python的特殊方法(魔术方法):
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other): # 实现+运算符
return Vector(self.x + other.x, self.y + other.y)
def __str__(self): # 定义对象的字符串表示
return f"Vector({self.x}, {self.y})"
常见特殊方法:
__init__
: 构造函数__str__
: 字符串表示__len__
: 定义len()行为__getitem__
: 实现索引访问__call__
: 使实例可调用million = 1_000_000 # 提高大数字可读性
bytes_val = 0xCAFE_F00D # 十六进制同样适用
match status_code:
case 200:
print("OK")
case 404:
print("Not found")
case _: # 匹配任何值
print("Unknown status")
_
前缀表示protected成员,__
前缀表示private成员__
前缀__
方法_
可以提高代码可读性,但过度使用会适得其反Q1: _
和__
有什么区别?
_
前缀:命名约定,提示protected成员__
前缀:名称改写,避免子类命名冲突__
前后缀:Python特殊方法Q2: 为什么我的__private
变量还能被访问?
__
前缀只是触发了名称改写obj._ClassName__private
访问,但不推荐这样做Q3: 什么时候应该使用下划线后缀?
class_
、type_
等在Python中,"显式优于隐式",下划线看似简单,实则内涵丰富,正是这一哲学的具体体现。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有