【问题标题】:Python: Passing Optional Arguments in Class InheritancePython:在类继承中传递可选参数
【发布时间】:2020-02-07 08:18:33
【问题描述】:

我不明白为什么我不能将可选参数设置为值。我总是收到一个空列表。我将参数设置为 Nonetype 以避免在那里使用可变类型。是因为我的父类疏忽而没有更新还是其他原因?

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])

【问题讨论】:

    标签: python class multiple-inheritance optional-arguments


    【解决方案1】:

    将参数传递给您的超类构造函数 :

    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__)
    

    【讨论】:

      猜你喜欢
      • 2019-09-25
      • 2018-04-03
      • 1970-01-01
      • 1970-01-01
      • 2018-05-25
      • 2014-12-25
      • 2011-12-28
      • 2015-05-04
      • 2014-06-05
      相关资源
      最近更新 更多