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.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f'Person({self.name})'
def __repr__(self):
return f"Person(name='{self.name}', age={self.age})"
Here’s what you’ll get:
>>> john = Person('John Cleese', age=80)
>>> repr(john)
"Person(name='John Cleese', age=80)"
>>> john2 = eval(repr(john))
>>> type(john2)
<class 'repr_person.Person'>
>>> id(john)
4472330616
>>> id(john2)
4472331736
Some collection objects, such as lists, call repr()
on their contents when they are turned into strings. This can make an object printed to the screen behave differently when it is on its own compared to when it is in the list:
class User:
def __init__(self, username, password):
self.username = username
self.password = password
def __str__(self):
return self.username
def __repr__(self):
return f"User(username='{self.username}', password='{self.password}')"
Here’s what you’ll get:
>>> from user import User
>>> u = User('jcleese', 'ParrotIsNoMore')
>>> str(u)
'jcleese'
>>> str([u])
"[User(username='jcleese', password='ParrotIsNoMore')]"
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.