➜ ~ cat -n test.py
1 class A(object):
2 def __init__(self):
3 self.__private()
4 self.public()
5
6 def __private(self):
7 print 'A.__private()'
8
9 def public(self):
10 print 'A.public()'
11
12 class B(A):
13 def __private(self):
14 print 'B.__private()'
15
16 def public(self):
17 print 'B.public()'
18
19 b=B()
➜ ~ python test.py
A.__private()
B.public()
为什么第3行执行的是A的__private()方法而不是B的__private()方法?
因为这是Python的规定,以双下划线开头的方法是私有方法,所以A
的初始化器只能看到它自己的__private
方法