I have seen various examples on How to use 'super' in python, but in all of these examples, there are no arguments being passed to the subclass' init method. Consider the following example.
Here is the base class:
class Animal(object):
def __init__(self, genus):
self.genus = genus
Now heres without using super:
class Dog(Animal):
def __init__(self, genus):
Animal.__init__(self, genus)
x = Dog('Canis')
print x.genus # Successfully prints "Canis"
Now when I use super instead:
class Dog(Animal):
def __init__(self, genus):
super(Animal, self).__init__(genus)
x = Dog('Canis')
print x.genus
I get the following error:
TypeError: object.__init__() takes no parameters
So then if object.init() takes no parameters, how to I set the specific genus of this particular animal when instantiated that subclass? Do I have to explicitly assign the variables like this:
class Dog(Animal):
def __init__(self, genus):
super(Animal, self).__init__()
self.genus = genus
Write:
class Dog(Animal):
def __init__(self, genus):
super(Dog, self).__init__(genus)
So instead of:
super(Animal, self).__init__(genus)
use:
super(Dog, self).__init__(genus)
Think of: What is the super class of Dog
? Animal
would be the right answer to this questions for this case. But if you use multiple inheritance this can be different.
If you use Python 3, all things get simpler:
class Dog(Animal):
def __init__(self, genus):
super().__init__(genus)
works. Much less surface for making a mistake.
If you need to work with Python 2, consider Python-Future. Than you can do this on Python 2:
from builtins import object, super
class Animal(object):
def __init__(self, genus):
self.genus = genus
class Dog(Animal):
def __init__(self, genus):
super().__init__(genus)
x = Dog('Canis')
print(x.genus)
This builtins
module comes from Python-Future. Using it, allows you to program Python 3 in Python 2 (at least for all important changes).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With