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