Dynamically choosing class to inherit from

后端 未结 5 1631
离开以前
离开以前 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:57

    Yep, you can do exactly what you wrote. Though personally, I'd probably do it this way for cleanliness:

    class _newClassNT(A):
        # class body
    
    class _newClassOther(B):
        # class body
    
    newClass = _newClassNT if os.name == 'nt' else _newClassOther
    

    This assumes that you need to actually do different things implementation-wise within the class body. If you only need to change the inheritance, you can just embed an if statement right there:

    class newClass(A if os.name == 'nt' else B):
        # class body
    

提交回复
热议问题