0
点赞
收藏
分享

微信扫一扫

Python中的下划线(_)

_LEON_ 2022-03-14 阅读 143

英文原文链接

内容汇总

  • 交互环境下的下划线
  • 出现在变量、函数、方法后面的单下划线
  • 出现在变量、函数、方法前面的单下划线
  • 出现在属性、方法前面的双下划线
  • 出现在方法前后的双下划线


 

交互环境下的下划线

在交互环境下,_用于存储上一个表达式的值,如下

>>> 40 + 20
60
>>> _ - 30
30

出现在变量、函数、方法后面的单下划线

根据转载出处所说,是为了避免和Python自带关键字冲突

>>> class MyClass():
... def __init__(self):
... print ("OWK")

>>> def my_defination(var1 = 1, class_ = MyClass):
... print (var1)
... print (class_)

>>> my_defination()
1
__main__.MyClass
>>>

出现在变量、函数、方法前面的单下划线

在上述地方之前出现了单个下划线,表示该变量(函数或方法)被希望只在它所出现的”内部“所使用,而不是被显式的在其他地方被调用。(PS:并不是不能,只是不希望被使用,比如)

>>>class A:
... def __init__(self):
... self.public = 10
... self._private = 12 # 希望能尽在内部使用
>>>
>>> a = A()
>>> a.public
10
>>> a._private # 但是依然还是可以访问
12

另外,如果使用from xxx import *这种语法导入模块的话,不会导入以_开头的变量和函数

# class_file.py

def public_api():
print ("public api")

def _private_api():
print ("private api")
>>> from class_file import *
>>> public_api()
public api

>>> _private_api()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '_private_api' is not defined

>>> import class_file
>>> class_file.public_api()
public api
>>> class_file._private_api()
private api

出现在属性、方法前面的双下划线

类似于其他语言中的private的效果。

假如某个属性和方法在变量名仅在前面被加了双下划线,表示该属性或方法只能被内部方法使用,而不能被外部显式的调用。和前文出现在属性和方法变量名前面的单下划线不同,这里是强制的,那边是建议的。

另外,也不是绝对不能使用这样的属性或者方法。如果要突破private的限制,只需要在使用的时候在前面添加"_类名"即可。

class Myclass():
def __init__(self):
self.__variable = 10
>>> obj = Myclass()
>>> obj.__variable # 尝试直接访问private属性
Traceback (most recent call last):
File "", line 1, in
AttributeError: Myclass instance has no attribute '__variable'
nce has no attribute 'Myclass'
>>>
>>>
>>> obj._Myclass__variable # 突破private的限制
10

出现在方法前后的双下划线

在前后都带有双下划线的方法表示的是一类特殊的方法。

有的时候它会有一些特殊的效果(比如会把__init__作为构造函数在对象新建时自动执行),有的时候它是作为运算符的重载出现(比如对自定义的类重载加减乘除等操作符)。

class Myclass():

def __init__(self, attr = 0):
self.attr = attr

def __add__(self, a):
return self.attr + a.attr
>>> a = Myclass(20)
>>> b = Myclass(30)
>>> a + b
50
举报

相关推荐

0 条评论