Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subclass - Arguments From Superclass

I'm a little confused about how arguments are passed between Subclasses and Superclasses in Python. Consider the following class structure:

class Superclass(object):     def __init__(self, arg1, arg2, arg3):         #Inilitize some variables         #Call some methods  class Subclass(Superclass):     def __init__(self):         super(Subclass, self).__init__()         #Call a subclass only method 

Where I'm having trouble is understanding how arguments are passed between the Superclass and Subclass. Is it necessary to re-list all the Superclass arguments in the Subclass initializer? Where would new, Subclass only, arguments be specified? When I try to use the code above to instantiate a Subclass, it only expects 1 argument, not the original 4 (including self) I listed.

TypeError: __init__() takes exactly 1 argument (4 given) 
like image 918
donopj2 Avatar asked Mar 23 '12 13:03

donopj2


People also ask

What does a subclass inherit from a superclass?

A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.

Can superclass access subclass variables?

A subclass inherits variables and methods from its superclass and can use them as if they were declared within the subclass itself: class Animal { float weight ; ...

Can subclass access the methods of superclass?

Does a subclass have access to the members of a superclass? No, a superclass has no knowledge of its subclasses.

What is the connection between the subclass and the superclass?

Definition: A subclass is a class that derives from another class. A subclass inherits state and behavior from all of its ancestors. The term superclass refers to a class's direct ancestor as well as all of its ascendant classes.


1 Answers

There's no magic happening! __init__ methods work just like all others. You need to explicitly take all the arguments you need in the subclass initialiser, and pass them through to the superclass.

class Superclass(object):     def __init__(self, arg1, arg2, arg3):         #Initialise some variables         #Call some methods  class Subclass(Superclass):     def __init__(self, subclass_arg1, *args, **kwargs):         super(Subclass, self).__init__(*args, **kwargs)         #Call a subclass only method 

When you call Subclass(arg1, arg2, arg3) Python will just call Subclass.__init__(<the instance>, arg1, arg2, arg3). It won't magically try to match up some of the arguments to the superclass and some to the subclass.

like image 177
Katriel Avatar answered Sep 20 '22 14:09

Katriel