THIS Makes Your Python Classes More READABLE

Amir Ali Hashemi
1 min readJul 20, 2023

Here is one quick tip that you can use with Python classes

In this example, we have a class called Fruit and we will initialize it with the name and the cost of the fruit. And it contains two methods:

class Fruit:
def __init__(self, name, cost):
self.name = name
self.cost = cost

def meth1(self):
pass

def meth2(self):
pass

At the bottom, we create an instance and we call it banana. We give it the name of “banana” with the cost of 10.5 Euros

banana = Fruit("banana", 10.5)
print(banana)

But now, printing the banana variable would give us this useless representation of our Fruit object and that doesn’t really tell us anything

<__main__.Fruit object at 0x7fb9f75fe550>

What we can do instead is call the dunder string method and inside the method you can return what you would want the string to look like when you print the object

class Fruit:
def __init__(self, name, cost):
self.name = name
self.cost = cost

def meth1(self):
pass

def meth2(self):
pass

def __str__(self):
return f"{self.name}, {self.cost}"

The next time we print the banana variable we’re going to get a beautiful representation of the banana:

banana, 10.5

--

--

Amir Ali Hashemi

I'm an AI student who attempts to find simple explanations for questions and share them with others