Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid specifying all arguments in a subclass

Tags:

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 which needs one extra arg (the last W)

class B(A):
    def __init__(self.a,b,c,d,e,f,g,...........,x,y,z,W)
        A.__init__(self,a,b,c,d,e,f,g,...........,x,y,z)
        self.__W=W

It seems dumb to write all this boiler-plate code, e.g passing all the args from B's Ctor to the inside call to A's ctor, since then every change to A's ctor must be applied to two other places in B's code.

I am guessing python has some idiom to handle such cases which I am unaware of. Can you point me in the right direction?

My best hunch, is to have a sort of Copy-Ctor for A and then change B's code into

class B(A):
     def __init__(self,instanceOfA,W):
         A.__copy_ctor__(self,instanceOfA)
         self.__W=W

This would suit my needs since I always create the subclass when given an instance of the father class, Though I am not sure whether it's possible...

like image 793
olamundo Avatar asked Feb 07 '10 04:02

olamundo


2 Answers

Considering that arguments could be passed either by name or by position, I'd code:

class B(A):
    def __init__(self, *a, **k):
      if 'W' in k:
        w = k.pop('W')
      else:
        w = a.pop()
      A.__init__(self, *a, **k)
      self._W = w
like image 105
Alex Martelli Avatar answered Oct 02 '22 20:10

Alex Martelli


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
like image 40
mechanical_meat Avatar answered Oct 02 '22 20:10

mechanical_meat