Skip to Content
Learn Python by Building Data Science Applications
book

Learn Python by Building Data Science Applications

by Philipp Kats, David Katz
August 2019
Beginner
482 pages
12h 56m
English
Packt Publishing
Content preview from Learn Python by Building Data Science Applications

__repr__ and __str__ 

These methods are assumed to return a string value that represents the object. The former is meant to be more strict and specific—ideally, you should be able to copy the outcome, run it as a code, and get an identical instance, like this:

class Animal:    def __init__(self, age, diet):        self.age = age        self.diet = diet        def __repr__(self):        return f"Animal(age={self.age}, diet='{self.diet}')"

This is what the representation of this class will look like:

>>> Animal(1, 'worms')Animal(age=1, diet='worms')

Indeed, if you copy that text and run it as a code, you'll get an identical copy. It should be noted, though, that far from all libraries follow that rule. 

The latter method, __str__, is meant to be more human-readable. If ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python for Data Science

Python for Data Science

Yuli Vasiliev
Introduction to Machine Learning with Python

Introduction to Machine Learning with Python

Andreas C. Müller, Sarah Guido

Publisher Resources

ISBN: 9781789535365Supplemental Content