Avoid specifying all arguments in a subclass

前端 未结 4 1913
悲哀的现实
悲哀的现实 2020-12-09 04:07

I have a class:

class A(object):
    def __init__(self,a,b,c,d,e,f,g,...........,x,y,z)
        #do some init stuff

And I have a subclass w

4条回答
  •  自闭症患者
    2020-12-09 04:38

    In situations where some or all of the arguments passed to __init__ have default values, it can be useful to avoid repeating the __init__ method signature in subclasses.

    In these cases, __init__ can pass any extra arguments to another method, which subclasses can override:

    class A(object):
        def __init__(self, a=1, b=2, c=3, d=4, *args, **kwargs):
            self.a = a
            self.b = b
            # …
            self._init_extra(*args, **kwargs)
    
        def _init_extra(self):
            """
            Subclasses can override this method to support extra
            __init__ arguments.
            """
    
            pass
    
    
    class B(A):
        def _init_extra(self, w):
            self.w = w
    

提交回复
热议问题