如何更改 Python 类的字符串表示形式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4912852/
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-18 18:05:25  来源:igfitidea点击:

How do I change the string representation of a Python class?

pythonstringpython-3.xprinting

提问by snakile

In Java, I can override the toString()method of my class. Then Java's print function prints the string representation of the object defined by its toString(). Is there a Python equivalent to Java's toString()?

在 Java 中,我可以覆盖toString()我的类的方法。然后 Java 的 print 函数打印由其toString(). 是否有与 Java 等效的 Python toString()

For example, I have a PlayCard class. I have an instance c of PlayCard. Now:

例如,我有一个 PlayCard 类。我有一个 PlayCard 的实例 c。现在:

>>> print(c)
<__main__.Card object at 0x01FD5D30>

But what I want is something like:

但我想要的是这样的:

>>> print(c)
A?

How do I customize the string representation of my class instances?

如何自定义我的类实例的字符串表示?

I'm using Python 3.x

我正在使用 Python 3.x

采纳答案by Mark Byers

The closest equivalent to Java's toStringis to implement __str__for your class. Put this in your class definition:

与 Java 最接近的等价物toString__str__为您的类实现。把它放在你的类定义中:

def __str__(self):
     return "foo"

You may also want to implement __repr__to aid in debugging.

您可能还想实施__repr__以帮助调试。

See here for more information:

浏览此处获取更多信息:

回答by seeg

This is not as easy as it seems, some core library functions don't work when only stris overwritten (checked with Python 2.7), see this thread for examples How to make a class JSON serializableAlso, try this

这并不像看起来那么容易,当仅覆盖str时,某些核心库函数不起作用(使用 Python 2.7 检查),请参阅此线程以获取示例 如何使类 JSON 可序列化另外,试试这个

import json

class A(unicode):
    def __str__(self):
        return 'a'
    def __unicode__(self):
        return u'a'
    def __repr__(self):
        return 'a'

a = A()
json.dumps(a)

produces

产生

'""'

and not

并不是

'"a"'

as would be expected.

正如预期的那样。

EDIT: answering mchicago's comment:

编辑:回答芝加哥的评论:

unicode does not have any attributes -- it is an immutable string, the value of which is hidden and not available from high-level Python code. The jsonmodule uses refor generating the string representation which seems to have access to this internal attribute. Here's a simple example to justify this:

unicode 没有任何属性——它是一个不可变的字符串,其值是隐藏的,无法从高级 Python 代码中获得。该json模块re用于生成似乎可以访问此内部属性的字符串表示。这是一个简单的例子来证明这一点:

b = A('b') print b

b = A('b') print b

produces

产生

'a'

'a'

while

尽管

json.dumps({'b': b})

json.dumps({'b': b})

produces

产生

{"b": "b"}

{"b": "b"}

so you see that the internal representation is used by some native libraries, probably for performance reasons.

所以你会看到一些本地库使用了内部表示,可能是出于性能原因。

See also this for more details: http://www.laurentluce.com/posts/python-string-objects-implementation/

有关更多详细信息,另请参见:http: //www.laurentluce.com/posts/python-string-objects-implementation/