Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Custom Data Types

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')]"

Comments & Discussion

Become a Member to join the conversation.