Dynamically choosing class to inherit from

后端 未结 5 1615
离开以前
离开以前 2021-02-02 07:30

My Python knowledge is limited, I need some help on the following situation.

Assume that I have two classes A and B, is it possible to do somet

5条回答
  •  醉话见心
    2021-02-02 07:49

    I have found my own way of dynamically inheriting classes when you have more than two options to chose from. I'm sure that others have used this before me, however I couldn't find anything like this online, therefore I thought that I should share it with you.

    class A():
        # Class A Body
    class B():
        # Class B Body
    class C():
        # Class C Body
    class D():
        # Class D Body
    def MakeObject(InheritedClassName): # InheritedClassName is a string
        def CheckClass(InheritedClass):
            if InheritedClass == "A":
                return A
            elif InheritedClass == "B":
                return B
            elif InheritedClass == "C":
                return C
            else:
                return D
        class WantedClass(CheckClass(InheritedClassName)):
            # WantedClass Body
        YourObject = WantedClass()
        return YourObject
    CreateObject = MakeObject(str(input("Chose A, B, C or D")))
    

    This code can be altered and you can do quite allot with it. This is my favorite way of setting up dynamic class inheritance, even though it's a bit long, as you can have as many options as you want and even could have multiple dynamically chosen inheritances for each object.

提交回复
热议问题