gpt4 book ai didi

python - 在对象字典上调用 str

转载 作者:太空宇宙 更新时间:2023-11-04 08:17:30 24 4
gpt4 key购买 nike

我有一个像这样的对象字典{'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)

关于python - 在对象字典上调用 str,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11670414/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com