Fix Python – Inheritance and Overriding __init__ in python


Asked By – liewl

I was reading ‘Dive Into Python’ and in the chapter on classes it gives this example:

class FileInfo(UserDict):
    "store file metadata"
    def __init__(self, filename=None):
        self["name"] = filename

The author then says that if you want to override the __init__ method, you must explicitly call the parent __init__ with the correct parameters.

  1. What if that FileInfo class had more than one ancestor class?
    • Do I have to explicitly call all of the ancestor classes’ __init__ methods?
  2. Also, do I have to do this to any other method I want to override?

Now we will see solution for issue: Inheritance and Overriding __init__ in python


The book is a bit dated with respect to subclass-superclass calling. It’s also a little dated with respect to subclassing built-in classes.

It looks like this nowadays:

class FileInfo(dict):
    """store file metadata"""
    def __init__(self, filename=None):
        super(FileInfo, self).__init__()
        self["name"] = filename

Note the following:

  1. We can directly subclass built-in classes, like dict, list, tuple, etc.

  2. The super function handles tracking down this class’s superclasses and calling functions in them appropriately.

This question is answered By – S.Lott

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0