Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize subclass parameters in python using super()

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
like image 468
Malonge Avatar asked Dec 31 '15 18:12

Malonge


1 Answers

The fix

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.

Python 3 for the rescue

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.

Python 3 niceties in Python 2 with Python-Future

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).

like image 99
Mike Müller Avatar answered Nov 15 '22 08:11

Mike Müller