Python Forum
Python dynamic inheritance ? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Python dynamic inheritance ? (/thread-3101.html)



Python dynamic inheritance ? - harun2525 - Apr-28-2017

ToggleWidgetClass = object

class SpecificToggleWdidgetClass(ToggleWidgetClass):
    def __init__(self, **kwargs):
        pass


def SpecificToggleWidget(var_ToggleWidgetClass = gtk.ToggleButton, **kwargs):
    global ToggleWidgetClass
    ToggleWidgetClass = var_ToggleWidgetClass

    return SpecificToggleWdidgetClass(**kwargs)
my problem is SpecificToggleWidgetClass not inheritancing again so it not changing when ToggleWidgetClass changed. is it impossible ?


RE: Python dynamic inheritance ? - Mekire - Apr-28-2017

You want a class factory?
class SomeBaseClass(object):
    def say_hello(self):
        print("Hi.")


class SomeOtherBaseClass(object):
    def say_hello(self):
        print("Yo.")


def class_factory(BaseClass):
    class SpecificClass(BaseClass):
        def __init__(self, *args, **kwargs):
            super(SpecificClass, self).__init__(*args, **kwargs)
    return SpecificClass
        

one = class_factory(SomeBaseClass)()
two = class_factory(SomeOtherBaseClass)()

for thing in (one,two):
    thing.say_hello()