• 技术文章 >常见问题 >Python常见问题

    Python3中_和__的用途和区别

    silencementsilencement2019-07-17 14:45:59原创1909

    在看一些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中双下划线开头,是为了不让子类重写该属性方法.通过类的实例化时自动转换,在类中的双下划线开头的属性方法前加上”_类名”实现.

    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 "<stdin>", line 1, in <module>
    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中没有真正的私有化,但是有一些和命名有关的约定,来让编程人员处理一些需要私有化的情况。

    专题推荐:单双下划线
    品易云
    上一篇:转行IT为什么必须学Python?Python的职业发展是什么? 下一篇:手把手教你用Python处理Excel表格

    相关文章推荐

    • Python的高级特性:容易忽略的不可变类型• 小白必看的Python函数讲解• 详解Python标准库

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网