Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python constructor of derived class

class baseClass():
  def __init__(self,mark,name):
    self.mark = mark
    self.name = name

class derivedClass(baseClass):

b1 = derivedClass(name='Jibin')
print b1.name

This was my code initially & it worked fine.

(Note: I don't have access to baseClass)

But later I had to pass a additional attribute rank to derivedClass.So I edited the code like this.

class baseClass():
  def __init__(self,mark,name):
    self.mark = mark
    self.name = name

class derivedClass(baseClass):
  def __init__(self,rank):
    self.rank = rank 

b1 = derivedClass(name='Jibin')
print b1.name

This caused an error __init__() got an unexpected keyword argument 'name'

This was expected as the __init__ of derivedClass do not have a argument name.

I don't want to add an additional argument name to __init__ of derivedClass b'cos in real baseClass has ten arguments instead of 2(mark,name) & if i give all them as additional argument to derivedClass I will be cluttering its argument list.

Note: I am aware of initializing baseClass using baseClass.__init__(self) or super(derivedClass, self).__init__()

like image 905
Jibin Avatar asked Dec 27 '22 11:12

Jibin


1 Answers

Maybe you can try something like this

class BaseClass(object):
  def __init__(self, mark=None, name=None):   # you're using named parameters, declare them as named one.
    self.mark = mark
    self.name = name

class DerivedClass(BaseClass):   # don't forget to declare inheritance
  def __init__(self, rank=None, *args, **kwargs):    # in args, kwargs, there will be all parameters you don't care, but needed for baseClass
    super(DerivedClass, self).__init__(*args, **kwargs)
    self.rank = rank 

b1 = DerivedClass(name='Jibin')
print b1.name
like image 163
Cédric Julien Avatar answered Jan 08 '23 11:01

Cédric Julien