3 回答

TA贡献1865条经验 获得超7个赞
实现__str__()或__repr__()在类的元类中。
class MC(type):
def __repr__(self):
return 'Wahaha!'
class C(object):
__metaclass__ = MC
print C
使用__str__,如果你说的是可读的字串,使用__repr__了明确的表示。

TA贡献1828条经验 获得超13个赞
class foo(object):
def __str__(self):
return "representation"
def __unicode__(self):
return u"representation"

TA贡献1829条经验 获得超6个赞
如果您必须在第一个之间进行选择__repr__或者选择__str__第一个,则默认情况下在未定义时执行__str__调用__repr__。
自定义Vector3示例:
class Vector3(object):
def __init__(self, args):
self.x = args[0]
self.y = args[1]
self.z = args[2]
def __repr__(self):
return "Vector3([{0},{1},{2}])".format(self.x, self.y, self.z)
def __str__(self):
return "x: {0}, y: {1}, z: {2}".format(self.x, self.y, self.z)
在此示例中,repr再次返回可以直接使用/执行的字符串,而str作为调试输出更有用。
v = Vector3([1,2,3])
print repr(v) #Vector3([1,2,3])
print str(v) #Vector(x:1, y:2, z:3)
添加回答
举报