Question
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):
UserDict.__init__(self)
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.
- What if that
FileInfo
class had more than one ancestor class?- Do I have to explicitly call all of the ancestor classes’
__init__
methods?
- Do I have to explicitly call all of the ancestor classes’
- 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
Answer
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:
-
We can directly subclass built-in classes, like
dict
,list
,tuple
, etc. -
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