Printing Objects
In this lesson, you'll learn how to print objects in Python.
We'll cover the following
Introduction to __str__
method
The print
method takes any number of arguments, converts each argument into a string by calling its __str__
method, and prints them. As with __init__
, that’s two underscores before
and after the name.
All classes have a __str__
method inherited from object
. It is a good idea to override this method. If you don’t, your objects will print something like this:
<__main__.Friend object at 0x1064728d0>
In the case of a Friend
object, your method might look something like this:
def __str__(self):
return self.name + "'s age is " + str(self.age)
print(meg)
would result in Margaret's age is 25
.
In the above example, Margret’s age is an integer, and we can’t add an integer to a string. Therefore, we had to explicitly convert her age to a string by calling the function str(self.age)
. Once you’ve defined the __str__
method in your class, you can call the str function
on objects of that class, by saying str(meg)
for example.
Technical note: Yes, you define the
__str__
method, then use it by calling thestr function
.
You can observe this in the example below:
Get hands-on with 1400+ tech skills courses.