Wednesday, March 16, 2022

Special methods

When we define a class in Python and try to print one of its instances using a print statement, we will get a string containing the class name and the reference of the object instance, which is the object's memory address. There is no default implementation of the to string functionality available with an instance or object. The code snippet showing this behavior is presented here:

#carexampl4.py

class Car:

def __init__(self, color, miles):

self.i_color = color

self.i_mileage = miles

if __name__ == "__main__":

car = Car ("blue", 1000)

print (car)

We will get console output similar to the following, which is not what is expected from a print statement:

<__main__.Car object at 0x100caae80>

To get something meaningful from a print statement, we need to implement a special __str__ method that will return a string with information about the instance and that can be customized as needed. Here is a code snippet showing the carexample4.py file with the __str__ method:

#carexample4.py

class Car:

c_mileage_units = "Mi"

def __init__(self, color, miles):

self.i_color = color

self.i_mileage = miles

def __str__(self):

return f"car with color {self.i_color} and \

mileage {self.i_mileage}"

if __name__ == "__main__":

car = Car ("blue", 1000)

print (car)

And the console output of the print statement is shown here:

car with color blue and mileage 1000

With a proper __str__ implementation, we can use a print statement without implementing special functions such as to_string(). It is the Pythonic way to control the string conversion. Another popular method used for similar reasons is __repr__,which is used by a Python interpreter for inspecting an object. The __repr__ method is more for debugging purposes.

These methods (and a few more) are called special methods or dunders, as they always start and end with double underscores. Normal methods should not use this convention.

These methods are also known as magic methods in some literature, but it is not the official terminology. There are several dozen special methods available for implementation with a class. A comprehensive list of special methods is available with the official Python 3 documentation at https://docs.python.org/3/reference/datamodel.html#specialnames.

In the next posts, we will study different object-oriented principles available in Python.

Share:

0 comments:

Post a Comment