5

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)

Bhargav Rao
  • 45,811
  • 27
  • 120
  • 136
aralar
  • 2,842
  • 6
  • 27
  • 42

2 Answers2

5

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.

behzad.nouri
  • 69,003
  • 18
  • 120
  • 118
3

One way will be to create a decorator that then creates a new class for us using type():

def modify_bases(bases):
    def decorator(cls):
        return type(cls.__name__, tuple(classes), dict(cls.__dict__))
    return decorator
...
>>> %cpaste
@modify_bases(classes)
class D:
    x = 1
    y = 2

>>> D.mro()
[<class '__main__.D'>, <class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>, <type 'object'>]
Ashwini Chaudhary
  • 232,417
  • 55
  • 437
  • 487