下划线在 Python 中的特殊含义

AI算法与图像处理

共 4850字,需浏览 10分钟

 · 2021-01-15


点击上方AI算法与图像处理”,选择加"星标"或“置顶

重磅干货,第一时间送达

Python 中的下划线


下划线在 Python 中是有特殊含义的,它们在 Python 的不同地方使用。


下面是 Python 中使用的不同类型的下划线:

1. 单下划线

保存上次执行的表达式的值


使用一个下划线保存 Python 交互式命令提示符中最后执行的表达式的值。我们还可以将值保存到另一个变量。

在循环中忽略值


在 Python 中使用一个下划线 _ 来忽略某些值。如果我们不想使用某些值,我们可以给将该值赋值给 _ 。

#Single underscore used in for loopfor _ in range(5):    print ("Python")
'''Output:PythonPythonPythonPythonPython'''
#Iterating through listcolors=["red","blue","green"]for _ in colors: print (_)'''Output:redbluegreen'''

忽略元组解压缩中的值


如果在元组解压缩时想要忽略某些值,可以将这些值分配给 _。

#tuple unpackingt=("red","green","blue")#ignoring value "green" while tuple unpackingt1,_,t2=tprint (t1)#Output:redprint (t2)#Output:blue

#Ignoring multiple values in tuple unpackingtt=(1,2,3,4,5,6)#Ignoring all values except first and last element in tuple.t3,*_,t4=ttprint (t3)print (t4)

用于数字分隔符


下划线也可以用作数字的分隔符,用于整数、浮点数和复数等数值中的数字分组。下划线没有语义含义,并且文字被解析,就像没有下划线一样。

#grouping decimal numbers by _a=10_000_000print (a)#Output:10000000

2. 单个前缀下划线


可以在变量名、方法名和类名中使用单个前缀下划线。它表示这些带有一个前缀下划线的类、变量和方法名称被程序视为“私有”。如果我们从 from M import * 中指定,那些以单个前缀下划线开头的名称将不会被导入。如果我们想导入这些变量/方法,我们必须在导入时指定名称。


引用 PEP-8:


_single_leading_underline:弱“ internal use” 指示符。例如:from m import * 不导入名称以下划线开头的对象。

#variable name having single leading underscore._a="hello"b="helloworld"
def add(x,y): print (x+y)#function name having single leading underscoredef _sub(x,y): print (x-y)
if __name__ == '__main__': print (_a)#Output:hello add(4,3)#Output:7 _sub(4,3)#Output:1

将上面提到的 Python 文件 c1.py import 至 c2.py


示例:from c1 import *


只有一个前缀下划线的变量和函数不能被访问。

from c1 import *#accessing variable names having single leading underscore.print (_a)#Output:NameError: name '_a' is not defined

#accessing function name havig single leading underscoreprint (_sub(7,2))#Output:NameError: name '_sub' is not defined

#accessing variables and functions which is not having single leading underscore.# we will able to access those varaibles and functionsadd(3,4)#Output:7print (b)#helloworld

如果我们想导入只有一个前缀下划线的变量和函数,那么在导入时必须提到这个变量名。


例如:from c1 import _a,_sub

from c1 import _a,_sub
#accessing variable names having single leading underscore.print (_a)#Output:hello

#accessing function name having single leading underscore_sub(7,2)#Output:5

3. 单个后缀下划线


单个后缀下划线用于避免与 Python 关键字冲突。


引用 PEP-8:


约定使用 single_trailing_underline_: 以避免与 Python 关键字冲突

list=[1,2,3]
t=(5,6,7)
#Coverting tuple to list using list() constructort1=list(t)#Output:TypeError: 'list' object is not callable

在上面的示例中,我们可以使用 list_ 作为变量名,以避免与 Python 关键字 list 发生冲突。

list_=[1,2,3]t=(5,6,7)#Coverting tuple to list using list() constructort1=list(t)print (t1)#Output:[5, 6, 7]

4. 双下划线


双下划线告诉 Python 解释器重写子类的属性名和方法名,以避免命名冲突。用类扩展名更改属性名称的解释器称为名称改写。


用 self._classname__methodname()代替 self.__methodname(),用


self._classname__attributename 代替 self.__attributename。


根据 Python 文档:


“名称改写有助于让子类重写方法,而不会破坏类内的方法调用。”


引用 PEP-8:


“ __double_leading_underline:当命名一个 class 属性时,调用名称改写(在类 FooBar 中,__boo 变成 _FooBar__boo)”

class Student:    def __init__(self,name,rollno):        self.name=name        self.__rollno=rollno    def __repr__(self):        return "{},{}".format(self.name,self.rollno)
s=Student("Karthi",12)
print (s.name)#Unable to access attributes having leading double underscore.print (s.__rollno)#Output:AttributeError: 'Student' object has no attribute '__rollno'#Name Mangling - have to use class extension with variable nameprint (s._Student__rollno)#Output: 12

具有相同方法名的继承类:

class A:    def __getmethod(self):        print ("Inside Class A")
class B(A): def __getmethod(self): print ("Inside Class B")
b=B()#Accessing __getmethod() in Class A using Name Manglingb._A__getmethod()#Output:Inside Class A#Accessing __getmethod() in Class B using Name Manglingb._B__getmethod()#Output:Inside Class B

5. 双前缀双后缀下划线


Python 中的特殊方法以双前缀和双后缀下划线命名。它们在 Python 中被称为 magic methods/dunder methods 方法。


例如:__init__,__str__,__repr__,__len__,这些神奇的方法在 Python 中有特殊的意义,我们可以覆盖它们来改变我们的类的特性。


引用 PEP-8:


__double_leading_and_trailing_underscore__:“ magic”对象或属性,位于用户控制的名称空间中。例如 __init__, __import____file__。永远不要发明这样的名称,只能根据记录使用。


根据 Python 约定,避免使用具有双前缀和双后缀下划线的变量名。


我们可以使用 dir()函数来查看类继承的神奇方法。

class Student:    def __init__(self,name,rollno):        self.name=name        self.rollno=rollno    def __repr__(self):        return "{},{}".format(self.name,self.rollno)
s=Student("karthi",12)print (s)#Output:karthi,12
print (dir(Student))'''Output:['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_'''


·  END  ·


HAPPY LIFE


下载1:何恺明顶会分享


AI算法与图像处理」公众号后台回复:何恺明,即可下载。总共有6份PDF,涉及 ResNet、Mask RCNN等经典工作的总结分析


下载2:终身受益的编程指南:Google编程风格指南


AI算法与图像处理」公众号后台回复:c++,即可下载。历经十年考验,最权威的编程规范!



下载3 CVPR2020

AI算法与图像处公众号后台回复:CVPR2020即可下载1467篇CVPR 2020论文
个人微信(如果没有备注不拉群!
请注明:地区+学校/企业+研究方向+昵称


觉得不错就点亮在看吧

浏览 21
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报