将对象实例列表从另一个 class 传递给方法
Passing a list of instances of object to the method from another class
我正在尝试传递另一个对象的 class 中的对象实例列表。当我直接这样做时——一切都在按预期进行。当他们传递列表时,它被包裹在一个元组中,它不起作用。
比较输出:
报告:
Record: None, None, None
Record: E001, IPTV and telematics, at Nov 20: everything is sad
Record: E002, DPI, None
for report1:
None
(<main.Record object at 0x7f7b88d65908>, <main.Record object at 0x7f7b88d65940>, <main.Record object at 0x7f7b88d65978>)
None
这怎么可能?以及如何修复它?
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())
在第一种情况下,您将 Record 实例作为单独的参数传递。在这种情况下,args
将是一个包含 3 个参数的元组。
在第二种情况下,您将传递一个参数,一个元组。与第一种情况一样,args
将是一个包含给定参数的元组:一个包含 Record 实例的元组。
如果您需要传递一个列表(或元组),目的是将每个列表项解释为一个单独的参数,use *
to unpack the list:
report1 = Report(*rec1.records)
我正在尝试传递另一个对象的 class 中的对象实例列表。当我直接这样做时——一切都在按预期进行。当他们传递列表时,它被包裹在一个元组中,它不起作用。 比较输出:
报告:
Record: None, None, None
Record: E001, IPTV and telematics, at Nov 20: everything is sad
Record: E002, DPI, None
for report1:
None
(<main.Record object at 0x7f7b88d65908>, <main.Record object at 0x7f7b88d65940>, <main.Record object at 0x7f7b88d65978>)
None
这怎么可能?以及如何修复它?
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())
在第一种情况下,您将 Record 实例作为单独的参数传递。在这种情况下,args
将是一个包含 3 个参数的元组。
在第二种情况下,您将传递一个参数,一个元组。与第一种情况一样,args
将是一个包含给定参数的元组:一个包含 Record 实例的元组。
如果您需要传递一个列表(或元组),目的是将每个列表项解释为一个单独的参数,use *
to unpack the list:
report1 = Report(*rec1.records)