Skip to content Skip to sidebar Skip to footer

Dynamically Derive A Class In Python

Possible Duplicate: Python dynamic inheritance: How to choose base class upon instance creation? I want a class to choose a base class on the fly based on a parameter in the ini

Solution 1:

While you can change the class in __init__, it's more appropriate to do it in __new__. The former is for initialising, the latter for construction:

classA(object): passclassB(object): passclassC(object):
    def__new__(cls, base_type, *args, **kwargs):
        returnsuper(C, cls).__new__(base_type, *args, **kwargs)

assertisinstance( C(A), A )
assertisinstance( C(B), B )

With __init__, you're creating an instance of C, and then modifying its type. With __new__, you're never creating an instance of C, just the required base_type.

Solution 2:

I assume you mean base_type insteand of parent type. But the following should work

Class C():
    def__init__(self, base_type):
        if base_type == 'A':
            self.__class__=A
        else:
            self.__class__=B

Some more details on this approach can be found here: http://harkablog.com/dynamic-state-machines.html

Solution 3:

I am completely agree with cyroxx, you should give us some context to your problem. As it stands now, __init__ is called after the instance of the class is created to initialize its members. Too late to change the inheritance.

Would a simple class factory be enough for you:

classMyA(ABMixin, A): passclassMyB(ABMixin, B): passdeffactory(class_type):
    if class_type == 'A':
        return MyA()
    else:
        return MyB()

I suggest to read this SO answer about dynamic class creation in python.

Post a Comment for "Dynamically Derive A Class In Python"