Search code examples
pythonclassmultiple-inheritanceoptional-arguments

Python: Passing Optional Arguments in Class Inheritance


I don't understand why I cannot set my optional arguments to values. I always receive an empty list. I have the argument set as Nonetype to avoid having a mutable type there instead. Is it not updating due to an oversight in my parent classes or am is it something else?

class Human:
  def __init__(self,first,last,age,nicknames=None):
    self.first =first
    self.last = last
    self.age = age

    if nicknames is None:
      self.nicknames = []
    else:
      self.nicknames = nicknames


class NFL_QB:
  def __init__(self,td,comeback,lst=None):
    self.td = td
    self.comeback = comeback

    if lst is None:
      self.lst = []
    else:
      self.lst = lst


class College_QB:
  def __init__(self,c_td,c_comeback):
    self.c_td = c_td
    self.c_comeback = c_comeback


class Player(Human,NFL_QB,College_QB):
  def __init__(self,first,last,age,td,comebacks,c_td,c_comebacks,nicknames=None,lst=None):
    Human.__init__(self,first,last,age,nicknames=None)
    NFL_QB.__init__(self,td,comebacks,lst=None)
    College_QB.__init__(self,c_td,c_comebacks)




ply = Player('tom','brady',42,532,55,32,21,['toutchdown tom'],[2016])

Solution

  • Pass the args down to your superclass constructors :

    class Player(Human,NFL_QB,College_QB):
      def __init__(self,first,last,age,td,comebacks,c_td,c_comebacks,nicknames=None,lst=None):
        Human.__init__(self,first,last,age,nicknames=nicknames) # You were passing `None` here
        NFL_QB.__init__(self,td,comebacks,lst=lst)  # ...and here.
        College_QB.__init__(self,c_td,c_comebacks)
    
    
    
    
    ply = Player('tom','brady',42,532,55,32,21,['toutchdown tom'],[2016])
    print(ply.__dict__)