对比Python中_,__,xx__xx

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

_ 的含义

`_xxx `不能用于’from module import *’ 以单下划线开头的表示的是protected类型的变量。即保护类型只能允许其本身与子类进行访问。

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

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

 

__的含义:

`__xxx` 双下划线表示的是私有类型的变量。只能是允许这个类本身进行访问了。连子类也不可以

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=A()
b=B()
a.method()
b.method()
 
输出:
 
This is a method from class A
This is a method from class A

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

#因此,在我们创建一个以"__"两个下划线开始的方法时,这意味着这个方法不能被重写,它只允许在该类的内部中使用。

在A中没有method方法,有的只是_Amethod方法,也可以在外面直接调用,所以python中没有真正的私有化,看下例:
a.__method()
#如果你试图调用a.__method,它还是无法运行的,就如上面所说,只可以在类的内部调用__method。


输出: --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-4-b8e0b1bf4d09> in <module>() ----> 1 a.__method() AttributeError: 'A' object has no attribute '__method'

 可以这样调用

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方法:
​
b=B()
b.method()
 
输出:
 
This is a method from calss B

__xx__前后双下划线

也叫魔术方法,就是不需要人为调用的方法,基本就是在特定的时间自动触发

例1:
name = "igor" 
name.__len__() 
 
输出:
4
 
例2:
number = 10 
number.__add__(20)
 
输出:
30

xx”经常是操作符或本地函数调用的magic methods。在上面的例子中,提供了一种重写类的操作符的功能。

在特殊的情况下,它只是python调用的hook。例如,init()函数是当对象被创建初始化时调用的;new()是用来创建实例。

class CrazyNumber(object):
    def __init__(self, n): 
        self.n = n 
    def __add__(self, other): 
        return self.n - other 
    def __sub__(self, other): 
        return self.n + other 
    def __str__(self): 
        return str(self.n) 
​
num = CrazyNumber(10) 
print(num)# 10
print(num + 5) # 5
print(num - 20) # 30   
 
 
输出: 
10
5
30
 
 
 
此文参考链接:
https://blog.csdn.net/m0_38063172/article/details/82179591
https://blog.csdn.net/yzl11/article/details/53792416
原文地址:https://www.cnblogs.com/-abm/p/9930663.html