Special string method __str__ in Python objects and how to use it

Anna Ikoki
2 min readJan 27, 2023

Double underscore special variables, attributes, functions, or methods or modules in python objects are user-defined overriding the formally defined one in a hierarchical manner. If defined by the user, they will override the in-built ones, else the formal definition will be used.

desk setup

Let’s see how we can customize __str__

class Player(object):
def __init__(self, age):
self.age = age
self.name = None
def get_age(self): #getter: methods to get out values
return self.age
def get_name(self):
return self.name
def set_age(self, newage):
self.age = newage
def set_name(self, newname=""):
self.name = newname

If we want to print out the object, we get the formal representation of the object <__main__.Player object at 0x...>

# instantiate Class and print 
player1 = Player(24)
print(player1)
# <__main__.Player object at 0x1043ac390>

# set name, then print the object
player1.set_name('Zonaldo')
print(player1)
# <__main__.Player object at 0x1043ac390>

# print using string method
print(Player.__str__(player1))
# <__main__.Player object at 0x1043ac390>

Here, what happens is the object calls the built-in string representation of an object using the built-in function object.__repr__()

--

--