[Python] How can I dynamically create derived classes from a base class

Discussão em 'Python' iniciado por Stack, Julho 22, 2025.

  1. Stack

    Stack Membro Participativo

    For example I have a base class as follows:

    class BaseClass(object):
    def __init__(self, classtype):
    self._type = classtype


    From this class I derive several other classes, e.g.

    class TestClass(BaseClass):
    def __init__(self):
    super(TestClass, self).__init__('Test')

    class SpecialClass(BaseClass):
    def __init__(self):
    super(TestClass, self).__init__('Special')


    Is there a nice, pythonic way to create those classes dynamically by a function call that puts the new class into my current scope, like:

    foo(BaseClass, "My")
    a = MyClass()
    ...


    As there will be comments and questions why I need this: The derived classes all have the exact same internal structure with the difference, that the constructor takes a number of previously undefined arguments. So, for example, MyClass takes the keywords a while the constructor of class TestClass takes b and c.

    inst1 = MyClass(a=4)
    inst2 = MyClass(a=5)
    inst3 = TestClass(b=False, c = "test")


    But they should NEVER use the type of the class as input argument like

    inst1 = BaseClass(classtype = "My", a=4)


    I got this to work but would prefer the other way, i.e. dynamically created class objects.

    Continue reading...

Compartilhe esta Página