Dynamically choosing class to inherit from

后端 未结 5 1614
离开以前
离开以前 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 08:01

    For those who have similar needs whilst working with different modules. First, create a fileswitcher.py and put inside it the following

    class Switcher():
        def choose(clname):
             Switcher.clname = clname
    

    Next, in your newClass.py put

    import switcher
    
    class newClass(switcher.Switcher.clname):
        ...
    

    Finally in your main script

    import switcher
    import os
        if os.name == 'nt':
            switcher.Switcher.choose(A):
        else:
            switcher.Switcher.choose(B):
    
    # that's the moment you're creating class with desired inheritance
    import newClass.newClass
    

提交回复
热议问题