如何为类对象创建自定义字符串表示形式? [英] How to create a custom string representation for a class object?
本文介绍了如何为类对象创建自定义字符串表示形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑这个类:
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?
推荐答案
实现 __ str __()
或 __ repr __()
类的元类。
class MC(type):
def __repr__(self):
return 'Wahaha!'
class C(object):
__metaclass__ = MC
print C
使用 __ str __
如果您的意思是可读的字符串,请使用 __ repr __
明确的表示。
Use __str__
if you mean a readable stringification, use __repr__
for unambiguous representations.
这篇关于如何为类对象创建自定义字符串表示形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文