1

I have this class:

class C(A,B):
    ....
    ....
    ....

I want to build a new class with the bases A,B , but i dont actually know which bases C has or how many.

Ive tried: class D(C.__bases__):

But I get the error:

TypeError: Error when calling the metaclass bases
list() takes at most 1 argument (3 given)

Now if I do: class D(C.__bases__[0],C.__bases__[1]),it works, but i need todo this without knowing how many bases are there.

Tried:

D(','.joing(C.__bases__)):

But this doesnt work as well

oz123
  • 27,559
  • 27
  • 125
  • 187
MichaelR
  • 969
  • 14
  • 36
  • I strongly recommend to read more: [PythonProgramming](http://en.wikibooks.org/wiki/Python_Programming/Metaclasses#Metaclasses) and [What is a metaclass in Python?](http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python/) – StefanNch May 18 '14 at 08:39

1 Answers1

3

To create a class with a dynamic set of bases, you'll have to use type():

def methodname1(self):
    pass

D = type('D', C.__bases__, {
    'attribute': 42,
    'methodname1': methodname1
})

type() takes the class name, a sequence of bases, and a dictionary of class attributes. These include all functions.

The above example is the equivalent of:

class D(A, B):
    attribute = 42

    def methodname1(self):
        pass

If C has a metaclass, you'd use that; if you are not sure if C has a metatype, use:

D = type(C)('D', C.__bases__, {
    'attribute': 42,
    'methodname1': methodname1
})

Python 3 makes this easier; there the sequence of parameters is treated like a function call, including support for * and ** expansions:

class D_in_python_3(*C.__bases__, metaclass=type(C)):
    pass
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343