如何为类对象创建自定义字符串表示形式?

考虑这个课程:


class foo(object):

    pass

默认字符串表示形式如下所示:


>>> str(foo)

"<class '__main__.foo'>"

如何将此显示设为自定义字符串?


慕丝7291255
浏览 497回答 3
3回答

莫回无

实现__str__()或__repr__()在类的元类中。class MC(type):&nbsp; def __repr__(self):&nbsp; &nbsp; return 'Wahaha!'class C(object):&nbsp; __metaclass__ = MCprint C使用__str__,如果你说的是可读的字串,使用__repr__了明确的表示。

慕田峪7331174

class foo(object):&nbsp; &nbsp; def __str__(self):&nbsp; &nbsp; &nbsp; &nbsp; return "representation"&nbsp; &nbsp; def __unicode__(self):&nbsp; &nbsp; &nbsp; &nbsp; return u"representation"

肥皂起泡泡

如果您必须在第一个之间进行选择__repr__或者选择__str__第一个,则默认情况下在未定义时执行__str__调用__repr__。自定义Vector3示例:class Vector3(object):&nbsp; &nbsp; def __init__(self, args):&nbsp; &nbsp; &nbsp; &nbsp; self.x = args[0]&nbsp; &nbsp; &nbsp; &nbsp; self.y = args[1]&nbsp; &nbsp; &nbsp; &nbsp; self.z = args[2]&nbsp; &nbsp; def __repr__(self):&nbsp; &nbsp; &nbsp; &nbsp; return "Vector3([{0},{1},{2}])".format(self.x, self.y, self.z)&nbsp; &nbsp; def __str__(self):&nbsp; &nbsp; &nbsp; &nbsp; return "x: {0}, y: {1}, z: {2}".format(self.x, self.y, self.z)在此示例中,repr再次返回可以直接使用/执行的字符串,而str作为调试输出更有用。v = Vector3([1,2,3])print repr(v)&nbsp; &nbsp; #Vector3([1,2,3])print str(v)&nbsp; &nbsp; &nbsp;#Vector(x:1, y:2, z:3)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python