【发布时间】:2017-04-28 08:39:38
【问题描述】:
我有一些数据对象,我想在这些数据对象上实现更深入的字符串和等于函数。
我实现了 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 包含相同的值,equals 返回 true(如预期的那样),而由于 t3 在列表中包含不同的值,因此结果为 false(也如预期的那样)。 我想要的是对 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 的类型(它们可能是列表,也可能是集合、字典等),因此如果有一个不需要类型检查的简单而优雅的解决方案,那就太好了...
这可能吗?
【问题讨论】:
-
你试过 json.dumps(your_object) 吗?
-
repr 如果对象在集合中而不是 str 则被调用
标签: python python-3.x tostring