Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Inherit the superclass __init__

I have a base class with a lot of __init__ arguments:

class BaseClass(object):     def __init__(self, a, b, c, d, e, f, ...):         self._a=a+b         self._b=b if b else a         ... 

All the inheriting classes should run __init__ method of the base class.

I can write a __init__() method in each of the inheriting classes that would call the superclass __init__, but that would be a serious code duplication:

class A(BaseClass):     def __init__(self, a, b, c, d, e, f, ...):         super(A, self).__init__(a, b, c, d, e, f, ...)  class B(BaseClass):     def __init__(self, a, b, c, d, e, f, ...):         super(A, self).__init__(a, b, c, d, e, f, ...)  class C(BaseClass):     def __init__(self, a, b, c, d, e, f, ...):         super(A, self).__init__(a, b, c, d, e, f, ...)  ... 

What's the most Pythonic way to automatically call the superclass __init__?

like image 240
Adam Matan Avatar asked Jun 30 '11 13:06

Adam Matan


People also ask

What does super () __ Init__ do in Python?

The “__init__” is a reserved method in python classes. It is known as a constructor in Object-Oriented terminology. This method when called, allows the class to initialize the attributes of the class. The super() function allows us to avoid using the base class name explicitly.

How do you inherit a class super in Python?

The Python super() method lets you access methods in a parent class. You can think of super() as a way to jump up to view the methods in the class from which another class is inherited. The super() method does not accept any arguments. You specify the method you want to inherit after the super() method.

Do subclasses need __ init __?

If, as is common, SubClass actually does want to have all of BaseClass 's invariants set up before it goes on to do its own customisation, then yes you can just call BaseClass. __init__() (or use super , but that's complicated and has its own problems sometimes). But you don't have to.

How does super () work in Python?

The super() function in Python makes class inheritance more manageable and extensible. The function returns a temporary object that allows reference to a parent class by the keyword super. The super() function has two major use cases: To avoid the usage of the super (parent) class explicitly.


1 Answers

super(SubClass, self).__init__(...) 

Consider using *args and **kw if it helps solving your variable nightmare.

like image 140
Andreas Jung Avatar answered Sep 26 '22 08:09

Andreas Jung