Python3中_和__的用途和区别

在看一些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.

在类TestA中定义了一个_method方法,按照约定是不能在类外面直接调用它的,为了可以在外面使用_method方法,又定义了method方法,method方法调用_method方法。

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

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 TestA

在类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 eval的用法及注意事项
下一篇:Python爬取13个旅游城市,告诉你五一大家最爱去哪玩?

PythonTab微信公众号:

Python技术交流互助群 ( 请勿加多个群 ):

群1: 87464755

群2: 333646237

群3: 318130924

群4: 385100854