Python3中_和__的用途和区别

图片[1]-Python3中_和__的用途和区别-uusu优素-乐高,模型,3d打印,编程

在看一些Python开源代码时,经常会看到以下划线或者双下划线开头的方法或者属性,到底它们有什么作用,又有什么样的区别呢?今天我们来总结一下(注:下文中的代码在Python3下测试通过)

_ 的含义

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

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

一般Python约定加了下划线 _ 的属性和方法为私有方法或属性,以提示该属性和方法不应在外部调用,也不会被from ModuleA import * 导入。如果真的调用了也不会出错,但不符合规范。

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

classTestA:
def_method(self):
print('Iamaprivatefunction.')
defmethod(self):
returnself._method()
ca=TestA()
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
ThisisamethodfromclassTestB

在类TestA中,__method方法其实由于name mangling技术的原因,自动转换成了_TestA__method,所以在A中method方法返回的是_TestA__method,TestB作为TestA的子类,只重写了__method方法,并没有重写method方法,所以调用B中的method方法时,调用的还是_TestA__method方法。

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

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

ca.__method()

输出

Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
AttributeError:'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方法。

总结

原文来自:https://www.py.cn
© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片快捷回复

    暂无评论内容