How to invoke the super constructor in Python?

class A: def __init__(self): print("world") class B(A): def __init__(self): print("hello") B() # output: hello In all other languages I’ve worked with the super constructor is invoked implicitly. How does one invoke it in Python? I would expect super(self) but this doesn’t work. Answers: Thank you for visiting the Q&A section on Magenaut. Please note that … Read more

Chain-calling parent initialisers in python

Consider this – a base class A, class B inheriting from A, class C inheriting from B. What is a generic way to call a parent class initialiser in an initialiser? If this still sounds too vague, here’s some code. class A(object): def __init__(self): print "Initialiser A was called" class B(A): def __init__(self): super(B,self).__init__() print … Read more

How does Python’s “super” do the right thing?

I’m running Python 2.5, so this question may not apply to Python 3. When you make a diamond class hierarchy using multiple inheritance and create an object of the derived-most class, Python does the Right Thing (TM). It calls the constructor for the derived-most class, then its parent classes as listed from left to right, then the grandparent. I’m familiar with Python’s MRO; that’s not my question. I’m curious how the object returned from super actually manages to communicate to calls of super in the parent classes the correct order. Consider this example code:

Python constructor and default value

Somehow, in the Node class below, the wordList and adjacencyList variable is shared between all instances of Node. >>> class Node: … def __init__(self, wordList = [], adjacencyList = []): … self.wordList = wordList … self.adjacencyList = adjacencyList … >>> a = Node() >>> b = Node() >>> a.wordList.append("hahaha") >>> b.wordList ['hahaha'] >>> b.adjacencyList.append("hoho") >>> … Read more

Simple python inheritance

class Animal(object): def __init__(self, nlegs=4): print '__init__ Animal' self.nlegs = nlegs class Cat(Animal): def __init__(self, talk='meow'): print '__init__ Cat' self.talk = talk class Dog(Animal): def __init__(self, talk='woof'): print '__init__ Dog' self.talk = talk Why does my cat tom = Cat() not have an nlegs attribute? Should we explicitly call Animal.__init__() from within Cat.__init__, or should … Read more