【问题标题】:object to string in PythonPython中的对象到字符串
【发布时间】:2017-04-28 08:39:38
【问题描述】:

我有一些数据对象,我想在这些数据对象上实现更深入的字符串和等于函数。

我实现了 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

由于 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


【解决方案1】:

您可以使用__repr__ 代替__str__,它以递归方式工作,尽管在大多数情况下这不是一个好主意(查看this 答案以获取更多详细信息)。不过,这对我有用:

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

【讨论】:

    【解决方案2】:

    您可以尝试使用 repr 代替 str

    当使用 def repr(self): 而不是 str 时,我得到了 print(t1) 的以下输出。

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

    如果这能解决您的问题,请告诉我。附上image供参考。

    问候, 维尼特

    【讨论】:

      猜你喜欢
      • 2011-09-04
      • 1970-01-01
      • 2022-06-10
      • 2018-12-08
      • 1970-01-01
      • 2012-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多