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
  • 50,140
  • 28
  • 121
  • 140
aralar
  • 3,022
  • 7
  • 29
  • 44

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
  • 74,723
  • 18
  • 126
  • 124
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
  • 244,495
  • 58
  • 464
  • 504