Python中的对象到字符串

Python中的对象到字符串,python,python-3.x,tostring,Python,Python 3.x,Tostring,我有一些数据对象,我想在这些对象上实现一个深入的to字符串和equals函数 我实施了str和eq,虽然平等很好,但我不能让str以同样的方式行事: class Bean(object): def __init__(self, attr1, attr2): self.attr1 = attr1 self.attr2 = attr2 def __str__(self): return str(self.__dict__)

我有一些数据对象,我想在这些对象上实现一个深入的to字符串和equals函数

我实施了streq,虽然平等很好,但我不能让str以同样的方式行事:

class Bean(object):

    def __init__(self, attr1, attr2):
        self.attr1 = attr1
        self.attr2 = attr2

    def __str__(self):
        return str(self.__dict__)

    def __eq__(self, other):
        return self.__dict__ == other.__dict__
当我跑步时:

t1 = Bean("bean 1", [Bean("bean 1.1", "same"), Bean("bean 1.2", 42)])
t2 = Bean("bean 1", [Bean("bean 1.1", "same"), Bean("bean 1.2", 42)])
t3 = Bean("bean 1", [Bean("bean 1.1", "different"), Bean("bean 1.2", 42)])

print(t1)
print(t2)
print(t3)
print(t1 == t2)
print(t1 == t3)
我得到:

{'attr2': [<__main__.Bean object at 0x7fc092030f28>, <__main__.Bean object at 0x7fc092030f60>], 'attr1': 'bean 1'}
{'attr2': [<__main__.Bean object at 0x7fc091faa588>, <__main__.Bean object at 0x7fc092045128>], 'attr1': 'bean 1'}
{'attr2': [<__main__.Bean object at 0x7fc0920355c0>, <__main__.Bean object at 0x7fc092035668>], 'attr1': 'bean 1'}
True
False
如果我这样做的话,这实际上是得到的:

Bean("bean 1", [Bean("bean 1.1", "same").__str__(), Bean("bean 1.2", 42).__str__()]).__str__
因为我不知道我的Bean对象中属性attr1、attr2的类型(它们可能是列表,但也可能是集合、字典等),所以最好有一个简单而优雅的解决方案,不需要进行类型检查


这可能吗?

您可以使用
\uuuu repr\uuuu
而不是递归工作的
\uuu str\uuuuuu
,尽管这在大多数情况下都不是一个好主意(有关更多详细信息,请参阅答案)。然而,这对我来说是可行的:

def __repr__(self):
    return str(self.__dict__)

您可以尝试使用repr而不是str

当使用defrepr(self)而不是str时,我得到了以下打印输出(t1)

{'attr1':'bean 1','attr2':[{'attr1':'bean 1.1','attr2':'same'},{'attr1':'bean 1.2','attr2':42}]}

让我知道这是否解决了你的问题。附上以供参考

问候,, Vinith

您是否尝试了json.dumps(您的_对象)?如果对象位于集合而不是str中,则会调用repr
def __repr__(self):
    return str(self.__dict__)