How to create a custom string representation for a class object?
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.
If you have to choose between __repr__
or __str__
go for the first one, as by default implementation __str__
calls __repr__
when it wasn't defined.
Custom Vector3 example:
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)
In this example, repr
returns again a string that can be directly consumed/executed, whereas str
is more useful as a debug output.
v = Vector3([1,2,3])
print repr(v) #Vector3([1,2,3])
print str(v) #x:1, y:2, z:3
class foo(object):
def __str__(self):
return "representation"
def __unicode__(self):
return u"representation"