当前位置: 首页 > 图灵资讯 > 行业资讯> 小白必看之Python3中_和__的用途和区别

小白必看之Python3中_和__的用途和区别

来源:图灵python
时间: 2025-03-07 22:08:25

看一些Python开源代码,经常会看到以下划线或双下划线开头的方法或属性。它们有什么作用,有什么区别?今天我们来总结一下(注:Python3下Python3下的代码测试合格)

_的含义

python类中没有真正的私有属性或方法,也没有真正的私有化。

然而,为了编程的需要,我们经常需要区分私有方法和共同方法,以便于管理和调用。那么如何在Python中做呢?

一般Python约定加下划线 _ 属性和方法是私有方法或属性,表明属性和方法不应在外部调用,也不应在from中使用 ModuleA import *导入。如果真的调用,不会出错,但不符合规范。

添加了以下代码演示_ 方法,以及类外对其的可访问性。

classTestA:
def_method(self):
print('Iamaprivatefunction.')
defmethod(self):
returnself._method()
ca=TestA()
ca.method()

输出:

Iamaprivatefunction.

在类Testa中定义了_method方法,根据协议不能直接在类外调用。为了在外面使用_method方法,还定义了method方法,method方法调用_method方法。

但我们应该记住的是,添加_的方法也可以在类外调用:

ca._method()

输出:

Iamaprivatefunction.

__的含义

Python中的__和name 与mangling技术有关,name mangling(又称name decoration命名修饰).在许多现代编程语言中,该技术用于解决命名冲突/重载等唯一名称引起的问题.

Python中双下划线的开头是为了防止子类重写属性方法。通过实例类的自动转换,将“_类名”添加到类中双下划线开头的属性方法中.

classTestA:
def__method(self):
print('ThisisamethodfromclassTestA')
defmethod(self):
returnself.__method()
classTestB(TestA):
def__method(self):
print('ThisisamethodfromcalssTestB')
ca=TestA()
cb=TestB()
ca.method()
cb.method()

输出结果:

ThisisamethodfromclassTestA
ThisisamethodfromclassTestA

在类Testa中,__method方法实际上是因为namesta mangling技术的原因自动转换为_TestA__method,因此,method方法在A中返回_TestA__method,Testb作为Testa的子类,只重写______________________________TestA__method方法。

注意:A中没有__method方法,只有_A__method方法,也可以直接在外面调用,因此python中没有真正的私有化

不能直接调用___method()方法, 转换后的方法需要调用

ca.__method()

输出

Traceback(mostrecentcalllast):
File"",line1,inAttributeError:'TestA'objecthasnoattribute'__method'

转换后的方法称为:_TestA__method

ca._TestA__method()

输出

ThisisamethodfromclassTestA

在TestB中重写method方法:

classTestB(TestA):
def__method(self):
print('ThisisamethodfromcalssTestB')
defmethod(self):
returnself.__method()
cb=B()
cb.method()

输出

ThisisamethodfromcalssTestB

现在TestB中的method方法将被调用_TestB__method方法:

总结:

python中没有真正的私有化,但有一些与命名相关的协议,要求编程人员处理一些需要私有化的情况。