When you pass an object to print()
, it converts it to a string using the str()
function. You can create a __str__()
method on your custom objects to change what is output:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f'Person({self.name})'
Here’s what you’ll get:
>>> from person import Person
>>> john = Person('John Cleese', 80)
>>> print(john)
Person(John Cleese)
The __str__()
method is meant to output a human-readable version of your object. There is also a __repr__()
method, which is meant for a Python representation of the object. There is a repr()
function that corresponds to the str()
function. If you define your __repr__()
properly, then eval()
can be called on its result to create a new object.
akolal on Jan. 7, 2021
I am having a real tough time seeing a dark blue font against a black background in the repl. Perhaps it is just me. But the choice in other videos were great. Please consider changing it.