Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python __init__ method in inherited class

Tags:

I would like to give a daughter class some extra attributes without having to explicitly call a new method. So is there a way of giving the inherited class an __init__ type method which does not override the __init__ method of the parent class?

I have written the code below purely to illustrate my question (hence the poor naming of attributes etc).

class initialclass():     def __init__(self):         self.attr1 = 'one'         self.attr2 = 'two'      class inheritedclass(initialclass):     def __new__(self):         self.attr3 = 'three'      def somemethod(self):         print 'the method'   a = inheritedclass()  for each in a.__dict__:     print each  #I would like the output to be: attr1 attr2 attr3 

Thank you

like image 984
Anake Avatar asked Apr 12 '11 13:04

Anake


1 Answers

As far as I know that's not possible, however you can call the init method of the superclass, like this:

class inheritedclass(initialclass):     def __init__(self):         initialclass.__init__(self)         self.attr3 = 'three' 
like image 90
Yexo Avatar answered Oct 08 '22 02:10

Yexo