I'm having a small amount of difficulty understanding inheritance in Python. I was under the impression that when Class B inherits from Class A it inherits all of the values that were initialized in A. I've made up an example to demonstrate what I mean:
Class A():
def __init__(self,parameter):
self.initialize_parameter=4*parameter
Class B(A):
def __init__(self):
pass
def function(self,another_parameter):
return self.initialize_parameter*another_parameter
But in this case, calling:
B_instance=B()
print B_instance.function(10)
Returns an AttributeError saying that class B doesn't not have self.initialized_parameter
So my question is, do I have to copy and paste all the initializations from A to B manually or is there a way that I can use them from within B without calling the A class itself? (I hope this is clear).
5 Answers 5
If you want to use the behaviour in the superclass' constructor you should either not override it:
Class B(A):
def function(self,another_parameter):
return self.initialize_parameter*another_parameter
Or if you want to extend the initialization behaviour you can use super()
Class B(A):
def __init__(self, parameter)
super(B, self).__init__(2*parameter)
def function(self,another_parameter):
return self.initialize_parameter*another_parameter
In Python 3 super() doesn't need explicit arguments (super().__init__()).
This general override behaviour and super() applies to all methods, not just constructors.
1 Comment
You have to use the super builtin in order to do the required initialisation for the parent class, like so:
class B(A):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
If you're not using Python 3, you might have to do it like this:
class B(A):
def __init__(self, *args, **kwargs):
super(A, self).__init__(*args, **kwargs)
Basically this calls A's __init__ function which is required if you want to reference A's methods and attributes.
Comments
The only way to initialize the base class is to use super().__init__() in B __init__() method. See: Understanding Python super() with __init__() methods
Comments
You are overriding the constructor from the super class here:
def __init__(self):
pass
So, self.initialize_parameter is never being initialized.
Delete that method, and it should work.
Comments
The __init__ of the superclass is only called automatically when you do not specify an __init__ in the subclass. So you should not define __init__ in class B unless you need to.
If you specify __init__ in class B you have to call __init__ in the superclass by hand. I prefer calling it this way: A.__init__(self,'provide_initialize_parameter_here'). Other people prefer using super.