如何更改 Python 类的字符串表示形式? [英] How do I change the string representation of a Python class?

查看:45
本文介绍了如何更改 Python 类的字符串表示形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中,我可以覆盖我的类的 toString() 方法.然后Java 的print 函数打印由它的toString() 定义的对象的字符串表示.是否有与 Java 的 toString() 等效的 Python?

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

<预><代码>>>>打印(c)<__main__.Card 对象在 0x01FD5D30>

但我想要的是:

<预><代码>>>>打印(c)♣

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

我使用的是 Python 3.x

解决方案

与 Java 的 toString 最接近的等价物是为您的类实现 __str__.把它放在你的类定义中:

def __str__(self):返回foo"

您可能还想实现 __repr__ 以帮助调试.

请参阅此处了解更多信息:

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()?

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

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

解决方案

The closest equivalent to Java's toString is to implement __str__ for your class. Put this in your class definition:

def __str__(self):
     return "foo"

You may also want to implement __repr__ to aid in debugging.

See here for more information:

这篇关于如何更改 Python 类的字符串表示形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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