【python】python _、__、__xx__之间的差别

 

本文来自 yzl11 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/yzl11/article/details/53792416?utm_source=copy 

单下划线、双下划线、头尾双下划线说明:

1. __foo__: 定义的是特殊方法,一般是系统定义名字 ,类似 __init__() 之类的。

当你看到"__this__"的时,就知道不要调用它。为什么?因为它的意思是它是用于Python调用的,如下

>>> name = "igor" >>> name.__len__() 4 >>> len(name) 4 >>> number = 10 >>> number.__add__(20) 30 >>> number + 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  

---------------------

另一个例子:

class Room(object):
    def __init__(self): 
        self.people = [] 
    def add(self, person): 
        self.people.append(person) 
    def __len__(self): 
        return len(self.people)
 
room = Room() 
room.add("Igor") 
print len(room) # 1

---------------------

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

class BaseForm(StrAndUnicode):
    ...
    
    def _get_errors(self):
        "Returns an ErrorDict for the data provided for the form"
        if self._errors is None:
            self.full_clean()
        return self._errors
    
    errors = property(_get_errors)

上面的代码片段来自于django源码(django/forms/forms.py)。这里的errors是一个属性,属于API的一部分,但是_get_errors是私有的,是不应该访问的,但可以通过errors来访问该错误结果。

3. __foo: 双下划线的表示的是私有类型(private)的变量, 只能是允许这个类本身进行访问了。

class A(object): 
    def __method(self): 
        print "I'm a method in A" 
    def method(self): 
        self.__method() a = A() a.method()

---------------------
输出:
I'm a method in A

给A添加子类

class B(A): 
    def __method(self): 
        print "I'm a method in B" 

b = B() 
b.method()
-------------------------------
输出:
I'm a method in A
原文地址:https://www.cnblogs.com/dhs94/p/9757971.html