对象到 Python 中的字符串 [英] object to string in Python

查看:35
本文介绍了对象到 Python 中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些数据对象,我想在这些对象上实现深入的 to string 和 equals 函数.

I have some data objects on which I want to implement a to string and equals functions that go in depth.

我实现了 streq,虽然相等效果很好,但我不能让 str 以同样的方式表现:

I implemented str and eq and although equality works fine I cannot make str behave in the same way:

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 字符串具有相同的行为(基本上也对列表(或 set 或 dict ...)中的元素进行深入研究.

since t1 and t2 contain the same values the equals return true (as expected) while since t3 contains a different value in the list the result is false (also as expected). What I would like is to have the same behavior for the to string (basically to also go in depth also for the elements in list (or set or dict ...).

对于 print(t1) 我想获得类似的东西:

For print(t1) I would like to obtain something like:

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

如果我这样做,实际上会获得:

which is actually obtained if I do:

Bean("bean 1", [Bean("bean 1.1", "same").__str__(), Bean("bean 1.2", 42).__str__()]).__str__

由于我不知道 Bean 对象中的属性 attr1、attr2(它们可能是列表,但也可能是集合、字典等)的类型,因此最好有一个不需要类型检查的简单而优雅的解决方案...

Since I do not know the types of the attributes attr1, attr2 in my Bean objects (they may be lists but also sets, dictionaries etc.) is would be nice to have a simple and elegant solution that would not require type checking ...

这可能吗?

推荐答案

您可以使用 __repr__ 代替 __str__,它以递归方式工作,尽管这不是一个好主意大多数时候(查看这个答案了解更多详情).尽管如此,这对我有用:

You can use __repr__ instead of __str__, which works recursively, although that is not a good idea most of the times (look at this answer for more details). Nevertheless, this works for me:

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

这篇关于对象到 Python 中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆