Reading Time: 1 minutes
Using __str__() in Python
Like the __init__() method, the __str__() method is one of several class methods which are called implicitly on certain events. These methods are called magic methods, or dunder methods, because of the double underscore in front of the method name. These methods need not be defined, but if defined, Python will execute them on certain events. The __str__ magic method is called when the object is printed, for example, while printing it. The __str__ is defined to return a string representation of the instance.
# When the __str__() is not defined >>> class Man: def __init__(self, name, age, weight, height): self.name = name self.age = age self.weight = weight self.height = height print("1.", self) >>> ethan = Man('Ethan', 10, 60, 100) 1. <__main__.Man object at 0x033D0710> # from print(self) >>> print(ethan) <__main__.Man object at 0x033D0710> # from print(instanceName) >>> >>> >>> >>> >>> # When the __str__() is defined >>> class Man: def __init__(self, name, age, weight, height): self.name = name self.age = age self.weight = weight self.height = height print("1.", self) def __str__(self): return "{} | {} | {} | {}".format(self.name, self.age, self.weight, self.height) >>> ethan = Man('Ethan', 10, 60, 100) 1. Ethan | 10 | 60 | 100 # from print(self) >>> print(ethan) Ethan | 10 | 60 | 100 # from print(instanceName)