Why does the child class does not inherit the method from parent class in python in this example?

The double underscore attributes have their names mangled based on the current/containing namespace. In the function foo, the current namespace is Foo so when python looks up self.__baz, it will actually look for self._Foo__baz due to the name mangling scheme. Since nowhere in Foo have you actually set an __baz attribute, the class has no _Foo__baz attribute (it has a _Bar__baz attribute since you set self.__baz in a method within Bar).

Of course, as you've probably noticed, if you call Foo.__init__(self) in Baz.__init__ (directly or via super), you'll see the problem go away because Foo.__init__ sets __baz (i.e. _Foo__baz).


When you name variables with double underscore like that in python the member name will be obfuscated. Declaring __baz gives you a member _Bar__baz.

class Bar(Foo):
 def __init__(self):
     #super(Bar, self).__init__()
     self.__baz = 21
 def bar(self):
     print self._Bar__baz

x = Bar()
x.bar()
>>> 21

By using the initial double underscores on __baz you requested "name mangling" to make a "private" variable. It's documented here:

http://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references

If you change the name from __baz to just baz your code will work as shown.