对象到 Python 中的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43675771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:16:22  来源:igfitidea点击:

object to string in Python

pythonpython-3.xtostring

提问by Valerian

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

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

I implemented strand eqand although equality works fine I cannot make strbehave in the same way:

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

When I run:

当我运行时:

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)

I get:

我得到:

{'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

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 ...).

由于 t1 和 t2 包含相同的值,equals 返回 true(如预期),而由于 t3 在列表中包含不同的值,结果为 false(也如预期)。我想要的是对 to 字符串具有相同的行为(基本上也对列表(或 set 或 dict ...)中的元素进行深入研究。

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

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

{'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__

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 ...

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

Is this possible ?

这可能吗 ?

回答by alexpeits

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

您可以使用__repr__代替__str__,它递归地工作,尽管大多数时候不是一个好主意(有关更多详细信息,请查看答案)。尽管如此,这对我有用:

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

回答by Vinith Srinivas

You can try using reprinstead of str.

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

I got the below output for print(t1), when using def repr(self): instead of str.

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

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

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

Let me know if this solves your problem. Attaching imagefor reference.

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

Regards, Vinith

问候, 维尼思