如何为类对象创建自定义字符串表示? [英] How to create a custom string representation for a class object?

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

问题描述

考虑这个类:

class foo(object):经过

默认的字符串表示如下所示:

<预><代码>>>>STR(富)<class '__main__.foo'>"

如何让这个显示自定义字符串?

解决方案

实施 __str__()__repr__() 在类的元类中.

类 MC(类型):def __repr__(self):返回哇哈哈!"C类(对象):__元类__ = MC打印(C)

使用 __str__ 如果您的意思是可读的字符串化,请使用 __repr__ 进行明确表示.

Consider this class:

class foo(object):
    pass

The default string representation looks something like this:

>>> str(foo)
"<class '__main__.foo'>"

How can I make this display a custom string?

解决方案

Implement __str__() or __repr__() in the class's metaclass.

class MC(type):
  def __repr__(self):
    return 'Wahaha!'

class C(object):
  __metaclass__ = MC

print(C)

Use __str__ if you mean a readable stringification, use __repr__ for unambiguous representations.

这篇关于如何为类对象创建自定义字符串表示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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