【问题标题】:Passing a list of instances of object to the method from another class将对象实例列表传递给另一个类的方法
【发布时间】:2016-11-20 21:02:59
【问题描述】:

我正在尝试传递另一个对象类中的对象实例列表。当我直接这样做时 - 一切都在正常工作。当他们通过时,列表被包裹在一个元组中,它不起作用。 比较输出:

对于报告:

记录:无、无、无

记录:E001,IPTV 和远程信息处理,11 月 20 日:一切都很悲伤

记录:E002、DPI、无

对于报告1:

无

(ma​​in.Record object at 0x7f7b88d65908>, ma​​in.Record object at 0x7f7b88d65940>, ma​​in.Record object at 0x7f7b88d65978 >)

无

这怎么可能?以及如何解决?

class Ticket:
  tickets = []
  def __init__(self, id=None, group=None):
    self.id = id
    self.group = group
    self.tickets.append(self)

class Record(Ticket):  
  records = []
  def __init__(self, ticket=None, comment=None):
    self.ticket = ticket
    self.comment = comment
    self.records.append(self)

  def __str__(self):
    if self.ticket != None:
      return 'Record: ' +  '{0}, {1}, {2}'.format(self.ticket.id, self.ticket.group, self.comment)

class Report:  
  def __init__(self, *args):
    self.records = list(args)

  def show_all(self):
    for record in self.records:
      print(record)


if __name__ == '__main__':
  t1 = Ticket('E001', 'IPTV and telematics')
  t2 = Ticket('E002', 'DPI')
  rec1 = Record(Ticket())
  rec2 = Record(t1, 'at Nov 20: everything is sad')
  rec3 = Record(t2)

  report = Report(rec1,rec2,rec3)
  print(report.show_all())

  report1 = Report(tuple(rec1.records))
  print(report1.show_all())

【问题讨论】:

    标签: python-3.x object instance


    【解决方案1】:

    在第一种情况下,您将 Record 实例作为单独的参数传递。在这种情况下,args 将是一个包含 3 个参数的元组。

    在第二种情况下,您传递一个参数,一个元组。与第一种情况一样,args 将是一个包含给定参数的元组:一个包含 Record 实例的元组。

    如果您需要传递一个列表(或元组)以将每个列表项解释为一个单独的参数,use * to unpack the list:

    report1 = Report(*rec1.records)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-09
      • 1970-01-01
      • 1970-01-01
      • 2017-03-04
      • 1970-01-01
      相关资源
      最近更新 更多