Can I choose the parent class of a class from a fixed set of parent classes conditionally in the __init__ function?

前端 未结 2 1996
孤街浪徒
孤街浪徒 2020-12-22 00:40

I have a child class with two parents with identical function names.

I need to decide (based on type of object being created) within the constructor (__init__<

2条回答
  •  無奈伤痛
    2020-12-22 01:07

    Python offers a lot of flexibility, but you're working against the class mechanisms the language offers. there is no way to do this "with out any additional effort" since you will be implementing your own mechanisms on top of what the language offers. Honestly, just forget about using multiple inheritance, because inheritance is not what you are describing, you want a proxy object that delegates to the appropriate object. Depending on your specific circumstances, this could look different, but this will get you going:

    In [1]: class A:
       ...:     def x (self):
       ...:         print('a')
       ...:
       ...: class B:
       ...:     def x (self):
       ...:         print('b')
       ...:
       ...: class C:
       ...:     def __init__(self, type_, *args, **kwargs):
       ...:         self.__wrapped = type_(*args, **kwargs)
       ...:     def __getattr__(self, attr):
       ...:         return getattr(self.__wrapped, attr)
       ...:
       ...:
    
    In [2]: C(A).x()
    a
    
    In [3]: C(B).x()
    b
    

    Note, the way C.__init__ is implemented, everything after the first argument is passed to the delegated type's constructor.

提交回复
热议问题