Python @ DjangoSpin

Object Oriented Python: Adding arguments to the __init__() of superclass - super()

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Adding arguments to the __init__() of superclass in Python

Adding arguments to the __init__() of superclass in Python

Like all other attributes and methods, the __init__() method of the superclass is inherited by the subclasses. If there is no __init__() method in the subclass, then the __init__() method of the superclass is called when the subclass is instantiated. If the subclass also defines an __init__() method, then it is called instead of the __init__() method of the superclass.

>>> class Automobile(object):
	def __init__(self, make):
		self.make = make
		print("Printing make from inside the base class:", make)
	def ignition(self):
		print("Igniting...")

		
>>> class Car(Automobile):
	def __init__(self, make):
		self.make = make
		print("Printing make from inside the derived class:", make)

		
>>> ferrari = Car('Ferrari')
Printing make from inside the derived class: Ferrari

Now, consider a situation where you want the __init__() method of your subclasses to have additional functionality along with the functionality already defined in the __init__() method of the superclass. To achieve this, you can use the builtin super() function.

>>> class Automobile(object):
	def __init__(self, make):
		self.make = make
		print("Doing something with the make")
	def ignition(self):
		print("Igniting...")

		
>>> class Car(Automobile):
	def __init__(self, make, horsepower):
		super(Car, self).__init__(make)
		self.horsepower = horsepower
		print("Doing something with the horsepower")

		
>>> ferrari = Car('Ferrari', 3200)
Doing something with the make
Doing something with the horsepower

super(Car, self).__init__(make) calls the __init__() method of the super class of Car passing the instance as an argument to it, in addition to the positional argument make. We could have easily replaced this statement with Automobile.__init__(self, make), but the super() function helps in decoupling the classes. If tomorrow, the superclass of Car changes from Automobile to, say, Cars, then we will have to change this particular statement inside the Car class as well.


See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply