我有一些数据对象,我想在这些对象上实现一个到字符串和等价函数的深入。
我实现了 str 和 eq,尽管相等函数工作得很好,但我不能让 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
因为t1和t2包含相同的值,所以等价返回真(如预期),而因为t3在列表中包含不同的值,所以结果为假(也如预期)。 我想要的是对to字符串有同样的行为(基本上也是对list(或set或dict...)中的元素进行深入分析。
对于print(t1),我希望得到类似的结果:
{'attr2': ["{'attr2': 'same', 'attr1': 'bean 1.1'}", "{'attr2': 42, 'attr1': 'bean 1.2'}"], 'attr1': 'bean 1'}
这实际上是得到的,如果我做:
Bean("bean 1", [Bean("bean 1.1", "same").__str__(), Bean("bean 1.2", 42).__str__()]).__str__
由于我不知道我的Bean对象中的属性attr1、attr2的类型(它们可能是列表,但也可能是集合、字典等),所以最好能有一个简单而优雅的解决方案,不需要类型检查...
这有可能吗?