Skip to main content
 首页 » 编程设计

python之在对象字典上调用 str

2025年05月04日16zhoujg

我有一个像这样的对象字典 {'name1':oject_instance_1,'name2':oject_instance_2,'name3':oject_instance_3} 在我的对象类定义中,我定义了 __str__() 方法 和 __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) 

工作正常。

有什么想法吗? 谢谢!

请您参考如下方法:

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

编辑:

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