1

我有一个像这样的对象字典 {'name1':oject_instance_1,'name2':oject_instance_2,'name3':oject_instance_3} 在我的对象类定义中,我定义__str__() method了方法和__repr__()方法,如下所示:

def __str__(self):
    return('{0} pathway containing {1} genes, with a total sequence length of {2}'.format(self.id, len(self.genes), self.length))

def __repr(self):
    return self.__str__    

如果重要的话 self.id 是一个字符串,self.genes 是一个列表,self.length 是一个 int

问题是当我去打印这本字典时,我得到:

{'pid1003': <Pathway.Pathway instance at 0x10169d680>, 'pid1002': <Pathway.Pathway instance at 0x10169d638>, 'pid1001': <Pathway.Pathway instance at 0x10169d5f0>}

但是像这样循环打印

for v in dict.values():
    print(v)

工作正常。

任何想法为什么?谢谢!

4

1 回答 1

6

也许你应该实施__repr__,而不是__repr

编辑:

并且__repr__应该返回一个字符串,而不是一个函数。因此,如评论中所述, return str(self)

于 2012-07-26T13:33:03.460 回答