在对象字典上调用str

Dav*_*agh 1 python oop string repr

我有一个像这样的对象的字典 {'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__    
Run Code Online (Sandbox Code Playgroud)

如果重要的是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>}
Run Code Online (Sandbox Code Playgroud)

但是像一个循环打印

for v in dict.values():
    print(v)
Run Code Online (Sandbox Code Playgroud)

工作良好.

有什么想法吗?谢谢!

小智 6

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

编辑:

并且__repr__应该返回一个String,而不是一个函数.所以,如评论中所述,返回str(self).