转载-python中的_和__

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

class A:
def _method(self):
print('约定为不在类的外面直接调用这个方法,但是也可以调用')
def method(self):
return self._method()
a = A()
1
2
3
4
5
6
在类A中定义了一个_method方法,按照约定是不能在类外面直接调用它的,为了可以在外面使用_method方法,又定义了method方法,method方法调用_method方法。请看代码演示:

In [24]: a.method()
不建议在类的外面直接调用这个方法,但是也可以调用
1
2
但是我们应该记住的是加了_的方法也可以在类外面调用:

In [25]: a._method()
不建议在类的外面直接调用这个方法,但是也可以调用
1
2
__ 的含义
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')
1
2
3
4
5
6
7
8
9
10
11
在类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
1
2
3
4
5
6
7
8
9
在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
1
2
3
4
5
6
7
8
9
10
在B中重写method方法:

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

def method(self):
return self.__method()
1
2
3
4
5
6
现在B中的method方法会调用_B__method方法:

In [32]: b = B()

In [33]: b.method()
This is a method from calss B
1
2
3
4
总结
python中没有真正的私有化,但是有一些和命名有关的约定,来让编程人员处理一些需要私有化的情况。
————————————————
版权声明:本文为CSDN博主「m0_38063172」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/m0_38063172/article/details/82179591

posted @ 2022-06-24 15:01  ZaleSwfit  阅读(198)  评论(0编辑  收藏  举报