15

I have the following classes:

class hello(object):
    def __init__(self):
        pass

class bye(object):
    def __init__(self):
        pass

l = [hello, bye]

If I do the following I get an error:

>>> class bigclass(*l):
  File "<stdin>", line 1
    class bigclass(*l):
                    ^
SyntaxError: invalid syntax

Is there another way to do this automatically at runtime?

I am using Python 2.7.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Har
  • 3,727
  • 10
  • 41
  • 75
  • 1
    I wonder what kind of problem you have, I've never thought about constructing classes with variable superclasses at runtime. – RemcoGerlich Dec 06 '13 at 14:11
  • I am attempting to define data models and controllers for those models through a text like interface where by the users connect the selected set of models at runtime to the selected controllers. – Har Dec 06 '13 at 14:58

2 Answers2

13

You could use the 3-argument form of type to create the class:

bigclass = type('bigclass', (hello, bye), {})
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
6

Using a Metaclass:

class Meta(type):

    def __new__(cls, clsname, bases, dct):
        bases = tuple(dct.pop('bases'))
        return type.__new__(cls, clsname, bases, dct)

class bigclass:

    __metaclass__ = Meta
    bases = l

print bigclass.__bases__
#(<class '__main__.hello'>, <class '__main__.bye'>)
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504