python中的_和__

版权声明:访问者可将本人原创或翻译内容或服务用于个人学习、研究或欣赏,以及其他非商业性或非盈利性用途,但同时应遵守著作权法及其他相关法律的规定,不得侵犯本人的合法权利。除此以外,将本人原创或翻译内容用于其他用途时,须征得本人的书面许可,并支付报酬。 https://blog.csdn.net/m0_38063172/article/details/82179591

Python中 _ 和 __ 的含义

_ 的含义

在python的类中,没有真正的私有化,不管是方法还是属性,为了编程的需要,约定加了下划线 _ 的属性和方法不属于API,不应该在类的外面访问,也不会被from M import * 导入。下面的代码演示加了_ 的方法,以及在类外面对其的可访问性。

class A:
    def _method(self):
        print('约定为不在类的外面直接调用这个方法,但是也可以调用')
    def method(self):
        return self._method()     
a = A()

在类A中定义了一个_method方法,按照约定是不能在类外面直接调用它的,为了可以在外面使用_method方法,又定义了method方法,method方法调用_method方法。请看代码演示:

In [24]: a.method()
不建议在类的外面直接调用这个方法,但是也可以调用

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

In [25]: a._method()
不建议在类的外面直接调用这个方法,但是也可以调用

__ 的含义

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

代码演示如下:

class A:

    def __method(self):
        print('This is a method from class A')

    def method(self):
        return self.__method()

class B(A):
    def __method(self):
        print('This is a method from calss B')

在类A中,__method方法其实由于name mangling技术的原因,变成了_A__method,所以在A中method方法返回的是_A__method,B作为A的子类,只重写了__method方法,并没有重写method方法,所以调用B中的method方法时,调用的还是_A__method方法:

In [27]: a = A()

In [28]: b = B()

In [29]: a.method()
This is a method from class A

In [30]: b.method()
This is a method from class A

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

In [35]: a.__method()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-35-b8e0b1bf4d09> in <module>()
----> 1 a.__method()

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

In [36]: a._A__method()
This is a method from class A

在B中重写method方法:

class B(A):
    def __method(self):
        print('This is a method from calss B')

    def method(self):
        return self.__method()

现在B中的method方法会调用_B__method方法:

In [32]: b = B()

In [33]: b.method()
This is a method from calss B

总结

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

猜你喜欢

转载自blog.csdn.net/m0_38063172/article/details/82179591