What is a clean “pythonic” way to implement multiple constructors?
I can’t find a definitive answer for this. As far as I know, you can’t have multiple __init__ functions in a Python class. So how do I solve this problem?
I can’t find a definitive answer for this. As far as I know, you can’t have multiple __init__ functions in a Python class. So how do I solve this problem?
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
Is there any difference at all between these classes besides the name?
Let’s say I have a class that has a member called data which is a list.
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
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:
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
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
Is there a copy constructor in python ? If not what would I do to achieve something similar ?