Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python multiple inheritance passing arguments to constructors using super

Consider the following snippet of python code

class A(object):     def __init__(self, a):         self.a = a  class B(A):     def __init__(self, a, b):         super(B, self).__init__(a)         self.b = b  class C(A):     def __init__(self, a, c):         super(C, self).__init__(a)         self.c = c  class D(B, C):     def __init__(self, a, b, c, d):         #super(D,self).__init__(a, b, c) ???         self.d = d 

I am wondering how can I pass a, b and c to corresponding base classes' constructors.

like image 545
Lin Avatar asked Jan 19 '16 18:01

Lin


People also ask

Can we use super in multiple inheritance in Python?

In fact, multiple inheritance is the only case where super() is of any use. I would not recommend using it with classes using linear inheritance, where it's just useless overhead.

What does super () __ init __ do?

Understanding Python super() with __init__() methods 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 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.

How does super () method play an important role in inheritance?

In a class hierarchy with single inheritance, super helps to refer to the parent classes without naming them explicitly, thus making the code more maintainable. Here, with the help of super(). f1(), the f1() method of the super class of Child class i.e Parent class has been called without explicitly naming it.


1 Answers

Well, when dealing with multiple inheritance in general, your base classes (unfortunately) should be designed for multiple inheritance. Classes B and C in your example aren't, and thus you couldn't find a proper way to apply super in D.

One of the common ways of designing your base classes for multiple inheritance, is for the middle-level base classes to accept extra args in their __init__ method, which they are not intending to use, and pass them along to their super call.

Here's one way to do it in python:

class A(object):     def __init__(self,a):         self.a=a  class B(A):     def __init__(self,b,**kw):         self.b=b         super(B,self).__init__(**kw)   class C(A):     def __init__(self,c,**kw):         self.c=c         super(C,self).__init__(**kw)  class D(B,C):     def __init__(self,a,b,c,d):         super(D,self).__init__(a=a,b=b,c=c)         self.d=d 

This can be viewed as disappointing, but that's just the way it is.

like image 105
shx2 Avatar answered Sep 22 '22 17:09

shx2