python _、__和__xx__的区别

"_"单下划线

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

 

"__"双下划线

以"__"两个下划线开始的方法时,这意味着这个方法不能被重写,它只容许在该类的内部中使用c++

让咱们来看一个例子:code

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

输出是这样的:blog

$ python example.py 
I'm a method in A

很好,出现了预计的结果。class

咱们给A添加一个子类,并从新实现一个__method:object

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

b = B() 
b.method()

如今,结果是这样的:
方法

$ python example.py
I'm a method in A

结论

  • 使用_one_underline来表示该方法或属性是私有的,不属于API;
  • 当建立一个用于python调用或一些特殊状况时,使用__two_underline__;
  • 使用__just_to_underlines,来避免子类的重写!
相关文章
相关标签/搜索