Python: Inherit the superclass __init__

前端 未结 7 898
囚心锁ツ
囚心锁ツ 2020-12-01 02:51

I have a base class with a lot of __init__ arguments:

class BaseClass(object):
    def __init__(self, a, b, c, d, e, f, ...):
        self._a=a+         


        
7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 03:02

    Perhaps a clearer implementation for your case is using **kwargs combined with new added arguments in your derived class as in:

    class Parent:
        def __init__(self, a, b, c):
            self.a = a
            self.b = b
            self.c = c
    
    
    class Child(Parent):
        def __init__(self, d, **kwargs):
            super(Child, self).__init__(**kwargs)
            self.d = d
    

    By this method you avoid the code duplication but preserve the implicit addition of arguments in your derived class.

提交回复
热议问题