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)
添加回答
舉報