7

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
1
  • 2
    The point of super is that you always use the current class. Commented Dec 31, 2015 at 18:43

1 Answer 1

15

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.