We often find our selves working with classes in python . And while debugging , if we print the instances , we will get a crazy output like
<main.{{class_name}} at 0x7f7a7bc76760>
In this small post we will learn to change the output produced by printing or viewing instances to something more sensible.
Lets say have a class Cat which currently does nothing .
class Cat :
pass
If we create an instance of it and print that . We will see an output like this .
persian = Cat()
print(persian)
# >> <__main__.Cat at 0x7f7a7bc76760>
The output prints the name of the class and the memory address of the instance
What is the good string representation of a class instance
An instance by default returns the memory address as its string representation . We don’t like it as it doesn’t help us with debugging in any sort , so what should it return instead ?
The best practice is that the string representation should be as same as the object initialization syntax .suppose we have a class Fraction which takes two arguments numerator and denominator .Then we can create an fraction like :
half = Fraction(1,2)
So the string representation of the class instance should be like Fraction(1,2) .
So , How can we achieve this .
To change the string representation of an instance, define the repr() .
For example:
class Fraction:
def __init__(self,numerator,demominator) :
self.numerator = numerator
self.demominator = demominator
def __repr__(self) :
return f"Fraction({self.numerator},{self.demominator})"
def __str__(self):
return f"{self.numerator}/{self.denominator}"
half = Fraction(1,2)
print(repr(half)) #repr() returns the string representation
# >> Fraction(1,2)
print(str(half))
# str() calls the __str__ method of the object to convert the object to str
# >> '1/2'
print(half)
# >> '1/2'
The _ _ repr _ _ () method returns the code representation of an instance, The built-in repr() function returns this text, as does the interactive interpreter when inspecting values. The _ _ str _ _ () method converts the instance to a string, and is the output produced by the str() and print() functions
Thanks for reading . Happy coding ..