如何在List中显示对象的字符串表示?

时间:2015-04-12 15:28:04

标签: python list python-2.7

我想显示一个对象表。此列表包含Step个对象。这是清单; `self.table:

class SegmentTable(object):
    ''' A segment table. '''
    def __init__(self, StepFactory):
        #self.fields = ((4,64), (27,32), (21,85), (43,32), (10,56), (28,56))
        self.fields = ((4,64), (27,32), (21,85))
        self.table = []
        self.step = StepFactory

    def __str__(self):
        return '\n'.join(self.table)

    def build(self):
        self.table = [self.step.generate(inc) for distance, inc in self.fields
            for i in xrange(distance)]

def main():
    factory = StepFactory()
    start = SegmentTable(factory)
    start.build()

    # This prints fine:
    for i in start.table:
        print i

    # This prints 'object at address (0xblahblahblah)'.
    print
    print start.table

if __name__ == '__main__':
    from step_factory import StepFactory
    main()

StepFactory只返回Step个对象)

以下是Step对象:

class Step(object):
    ''' A step. '''
    rnlut = (0xB1,0xFE)

    def __init__(self, stepid, offset, danger, inc):
        self.stepid = stepid
        self.offset = offset
        self.danger = danger
        self.rnd = (self.rnlut[self.stepid] - self.offset) & 0xFF
        self.limit = (self.rnd + 1) * 256
        self.enc = self.danger > self.limit
        self.input = None
        self.type = 'R'
        self.inc = inc

    def __str__(self):
        return '{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}'.format(
            self.stepid, self.offset, self.inc, self.danger, self.limit, self.rnd,
            self.enc, self.input, self.type)

我也在SegmentTable尝试了这个:

def __str__(self):
    return [str(step) for step in self.table]

输出

 <step.Step object at 0x000000000203EFD0> (many of these)

我希望print start.table正确打印Step对象。这可以简单地完成吗?

或者我必须求助于遍历每个项目并手动print吗?

0 个答案:

没有答案