python _、__和__xx__的区别

_xx 单下划线开头

Python中没有真正的私有属性或方法,可以在你想声明为私有的方法和属性前加上单下划线,以提示该属性和方法不应在外部调用.如果真的调用了也不会出错,但不符合规范.

Python中不存在真正的私有方法。为了实现类似于c++中私有方法,可以在类的方法或属性前加一个“_”单下划线,意味着该方法或属性不应该去调用,它并不属于API。

#!/usr/bin/env python
# coding:utf-8
class Test():
    def __init__(self):
        pass
    def _one_underline(self):  # 定义私有方法,都只能被类中的函数调用,不能在类外单独调用
        print "_one_underline"
    def __two_underline(self): # 防止类被覆盖,都只能被类中的函数调用,不能在类外单独调用
        print "__two_underline"

    def output(self):
        self._one_underline()
        self.__two_underline()
if __name__ == "__main__":

    obj_test=Test()
    obj_test.output()
'''
#输出结果为:
localhost:attempt_underline a6$ python undeline.py
_one_underline
__two_underline
'''

"__"双下划线

这个双下划线更会造成更多混乱,但它并不是用来标识一个方法或属性是私有的,真正作用是用来避免子类覆盖其内容。

让我们来看一个例子:

#!/usr/bin/env python
# coding:utf-8
class A(object):
    def __method(self):
        print "I'm a method in A"
    def method(self):
        self.__method()
        
class B(A):
    def __method(self):
        print "I'm a method in B"

if __name__ == "__main__":
    a = A()
    a.method()
    b = B()
    b.method()
‘’‘
# 输出结果为:
localhost:attempt_underline a6$ python undeline.py
I'm a method in A
I'm a method in A
’‘’

我们给A添加一个子类,并重新实现一个__method:

就像我们看到的一样,B.method()不能调用B.__method的方法。实际上,它是"__"两个下划线的功能的正常显示。

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

"__xx__"前后各双下划线
当你看到"__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)
        self.people.append(person)
        self.people.append(person)

    def __len__(self):
        return len(self.people)


room = Room()
room.add("Igor")
print len(room)  # 3

结论

  • 使用_one_underline来表示该方法或属性是私有的,不属于API;
  • 当创建一个用于python调用或一些特殊情况,如子类不能覆盖的那些父类方法时,使用__two_underline__;
  • 使用__just_to_underlines,来避免子类的重写!

参考:http://igorsobreira.com/2010/09/16/difference-between-one-underline-and-two-underlines-in-python.html

        https://www.cnblogs.com/coder2012/p/4423356.html


猜你喜欢

转载自blog.csdn.net/helloxiaozhe/article/details/80534894