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
It's incredibly simple. Define a new
__init__
method and call the parent's__init__
at the beginning.In Python 3, you don't have to (and therefore propably shouldn't, for simplicity) explicitly inherit from
object
or pass the class andself
tosuper
.Just call a designated method from the parent's init, if it exists:
As far as I know that's not possible, however you can call the init method of the superclass, like this:
Just call the parent's
__init__
usingsuper
:I strongly advise to follow Python's naming conventions and start a class with a Capital letter, e.g.
InheritedClass
andInitialClass
. This helps quickly distinguish classes from methods and variables.First of all you're mixing
__init__
and__new__
, they are different things.__new__
doesn't take instance (self
) as argument, it takes class (cls
). As for the main part of your question, what you have to do is usesuper
to invoke superclass'__init__
.Your code should look like this: