Python培训之_和__的用途和区别

发布时间:2022-11-28 09:45:06 人气:124 作者:多测师

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

  _ 的含义

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

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

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

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

  class TestA:

  def _method(self):

  print('I am a private function.')

  def method(self):

  return self._method()

  ca = TestA()

  ca.method()

  输出

  I am a private function.

  __ 的含义

  Python中的__和一项称为name mangling的技术有关,name mangling (又叫name decoration命名修饰).在很多现代编程语言中,这一技术用来解决需要唯一名称而引起的问题,比如命名冲突/重载等.

  Python中双下划线开头,是为了不让子类重写该属性方法.通过类的实例化时自动转换,在类中的双下划线开头的属性方法前加上”_类名”实现.

Python培训之_和__的用途和区别

  class TestA:

  def __method(self):

  print('This is a method from class TestA')

  def method(self):

  return self.__method()

  class TestB(TestA):

  def __method(self):

  print('This is a method from calss TestB')

  ca = TestA()

  cb = TestB()

  ca.method()

  cb.method()

  输出结果

  This is a method from class TestA

  This is a method from class TestB

  在类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 (most recent call last):

  File "", line 1, in

  AttributeError: 'TestA' object has no attribute '__method'

  转换后的方法名为:_TestA__method

  ca._TestA__method()

  输出

  This is a method from class TestA

  在TestB中重写method方法:

  class TestB(TestA):

  def __method(self):

  print('This is a method from calss TestB')

  def method(self):

  return self.__method()

  cb = B()

  cb.method()

  输出

  This is a method from calss TestB

  现在TestB中的method方法会调用_TestB__method方法。

  总结

  python中没有真正的私有化,但是有一些和命名有关的约定,来让编程人员处理一些需要私有化的情况。

  以上内容为大家介绍了Python培训之_和__的用途和区别,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注多测师。https://www.e70w.com/xwzx/


返回列表
在线客服
联系方式

热线电话

17727591462

上班时间

周一到周五

二维码
线