__repr__ and __str__

Through the __str__ method we can change the format of the object which we get upon inspecting and printing, as per below example 


class Device:
def __init__(self):
self.username = "root"
self.ip = "192.168.120.10"
self.device = "Linux"
def __repr__(self):
"""
called upon inspect
"""
return f"Test"
def __str__(self):
"""Called upon calling a print upon the object"""
return f"{self.device}/{self.username}@{self.ip}
class RawDevice:
def __init__(self):
pass
if __name__ == "__main__":
print(RawDevice())
print(Device())

$python3 pythonSpecials.py <__main__.RawDevice object at 0x103fab5f8> Linux/root@192.168.120.10


In the example above, when we print an object we get something like  
<__main__.RawDevice object at 0x103fab5f8>
which is little not informative, but upon modifying it in the Device, it gives us a nice view of it.

The __repr__ method is call when the object is inspected on the console, however the __str__ is called upon calling print on it.

Comments

Popular Posts