Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python inheritance and calling parent class constructor

Tags:

python

oop

This is what I'm trying to do in Python:

class BaseClass:
    def __init__(self):
        print 'The base class constructor ran!'
        self.__test = 42

class ChildClass(BaseClass):

    def __init__(self):
        print 'The child class constructor ran!'
        BaseClass.__init__(self)

    def doSomething(self):
        print 'Test is: ', self.__test


test = ChildClass()
test.doSomething()

Which results in:

AttributeError: ChildClass instance has no attribute '_ChildClass__test'

What gives? Why doesn't this work as I expect?

like image 378
Keith Palmer Jr. Avatar asked Jul 16 '09 19:07

Keith Palmer Jr.


2 Answers

From python documentation:

Private name mangling: When an identifier that textually occurs in a class definition begins with two or more underscore characters and does not end in two or more underscores, it is considered a private name of that class. Private names are transformed to a longer form before code is generated for them. The transformation inserts the class name in front of the name, with leading underscores removed, and a single underscore inserted in front of the class name. For example, the identifier __spam occurring in a class named Ham will be transformed to _Ham__spam. This transformation is independent of the syntactical context in which the identifier is used. If the transformed name is extremely long (longer than 255 characters), implementation defined truncation may happen. If the class name consists only of underscores, no transformation is done.

So your attribute is not named __test but _BaseClass__test.

However you should not depend on that, use self._test instead and most python developers will know that the attribute is an internal part of the class, not the public interface.

like image 68
Wojciech Bederski Avatar answered Sep 28 '22 08:09

Wojciech Bederski


You could use Python's introspection facilities to get you the information you are looking for. A simple dir(test) will give you

['_BaseClass__test', '__doc__', '__init__', '__module__', 'doSomething']

Note the '_BaseClass__test'. That's what you're looking for.

Check this for more information.

like image 42
partoa Avatar answered Sep 28 '22 06:09

partoa