Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheriting from classes unpacked from a list

Say I have a list of class objects in Python (A, B, C) and I want to inherit from all of them when building class D, such as:

class A(object):
    pass

class B(object):
    pass

class C(object):
    pass


classes = [A, B, C]

class D(*classes):
    pass

Unfortunately I get a syntax error when I do this. How else can I accomplish it, other than by writing class D(A, B, C)? (There are more than three classes in my actual scenario)

like image 894
aralar Avatar asked Jun 04 '15 01:06

aralar


People also ask

Is it possible for classes to inherit from each other?

It is not possible.

How does Python inheritance work?

Inheritance allows us to define a class that inherits all the methods and properties from another class. Parent class is the class being inherited from, also called base class. Child class is the class that inherits from another class, also called derived class.

How do you inherit a class from another file in Python?

Creating a class that inherits from another class To create a class that inherits from another class, after the class name you'll put parentheses and then list any classes that your class inherits from. In a function definition, parentheses after the function name represent arguments that the function accepts.

How does Python support multiple inheritance?

A class can be derived from more than one base class in Python, similar to C++. This is called multiple inheritance. In multiple inheritance, the features of all the base classes are inherited into the derived class. The syntax for multiple inheritance is similar to single inheritance.


1 Answers

You can dynamically create classes using type keyword, as in:

>>> classes = [A, B, C]
>>> D = type('D', tuple(classes), {})
>>> type(D)
<class 'type'>
>>> D.__bases__
(<class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>)

see 15247075 for more examples.

like image 65
behzad.nouri Avatar answered Oct 04 '22 16:10

behzad.nouri