Legends ofPythos
Claim your name
Objects and Classes

Making objects print nicely

Lesson 6 of 13

Watch the lesson5:45 ยท with Torsten
When you create a custom class and try to print an instance of it, Python gives you something like <__main__.Dog object at 0x7f...>. It tells you the type and memory address, but not what your data actually is. That's helpful for debugging in some cases, but mostly just noise.

__str__ vs __repr__

class Dog:
    def __init__(self, name):
        self.name = name

dog = Dog('Rex')
print(dog)  # <__main__.Dog object at 0x...>
print(str(dog))  # the same text
__str__ is what print() and str() use. It should be a human-friendly summary of the object.

__repr__ is meant for developers: an unambiguous representation, ideally something you could copy-paste back into Python to recreate the object.
class Dog:
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return f'Dog({self.name})'

dog = Dog('Rex')
print(dog)  # Dog(Rex)

__eq__: comparing objects by data

class Dog:
    def __init__(self, name):
        self.name = name

d1 = Dog('Rex')
d2 = Dog('Rex')
print(d1 == d2)  # False: two separate dogs
By default, == checks identity (same object), not equality of contents. To compare by data, implement __eq__. It receives the other object and returns True or False, or NotImplemented when it doesn't know how to compare itself with that kind of object.
class Dog:
    def __init__(self, name):
        self.name = name

    def __eq__(self, other):
        if not isinstance(other, Dog):
            return NotImplemented
        return self.name == other.name

d1 = Dog('Rex')
d2 = Dog('Rex')
print(d1 == d2)  # True

__len__: how many items?

class Playlist:
    def __init__(self, songs):
        self.songs = list(songs)

p = Playlist(['A', 'B'])
print(len(p))  # stops with a TypeError
len() calls a method called __len__(). A Playlist has none, so len(p) stops with TypeError: object of type 'Playlist' has no len(). If your class holds a list (or another collection), write __len__ so you can ask "how big is this?" directly. For example, add def __len__(self): to Playlist, with one line inside it: return len(self.songs). Then len(p) gives 2. Like __str__, it returns its answer; for __len__, that's a whole number.

Your turn

0 of 3 solved

Exercise 1

+35 XP
Define a class Book whose __init__ stores title. Write __str__ so it returns the text 'Book: <title>', for example 'Book: Dune': __str__ returns the text, and print() shows it. Also write __repr__, returning "Book('<title>')", for example Book('Dune'), with the title in single quotes. You write __repr__ just like __str__: def __repr__(self): with a return line inside.
Write your Python here.

Run your code to check it against the tests.

Exercise 2

+35 XP
Define a class Point whose __init__ stores x and y. Write __eq__ so two Point objects are equal if they have the same x and the same y.
Write your Python here.

Run your code to check it against the tests.

Exercise 3

+35 XP
Define a class Inventory whose __init__ takes a list of item names. Write __len__ so len() of an inventory gives the number of items, and __str__ returning 'Inventory(n)', where n is the count, for example 'Inventory(3)'. You write __len__ just like __str__ (def __len__(self): with a return line inside), but it returns a whole number, and len() gives back what it returns.
Write your Python here.

Run your code to check it against the tests.