Avoid specifying all arguments in a subclass

前端 未结 4 1917
悲哀的现实
悲哀的现实 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:37

    Edit: based on Matt's suggestion, and to address gnibbler's concern re a positional-argument approach; you might check to make sure that the additional subclass-specific argument is being specified—similar to Alex's answer:

    class B(A):
      def __init__(self, *args, **kwargs):
        try:
          self._w = kwargs.pop('w')
        except KeyError:
          pass
        super(B,self).__init__(*args, **kwargs)
    
    >>> b = B(1,2,w=3)
    >>> b.a
    1
    >>> b.b
    2
    >>> b._w
    3
    

    Original answer:
    Same idea as Matt's answer, using super() instead.

    Use super() to call superclass's __init__() method, then continue initialising the subclass:

    class A(object):
      def __init__(self, a, b):
        self.a = a
        self.b = b
    
    class B(A):
      def __init__(self, w, *args):
        super(B,self).__init__(*args)
        self.w = w
    

提交回复
热议问题