How To Use the __str__() and __repr__() Methods in Python | DigitalOcean (2024)

Introduction

In this article, you’ll learn about the special methods __str__() and __repr__() that are defined in the Python data model. The __str__() and __repr__() methods can be helpful in debugging Python code by logging or printing useful information about an object.

Python special methods begin and end with a double underscore and are informally known as dunder methods. Dunder methods are the underlying methods for Python’s built-in operators and functions. You should avoid calling dunder methods directly, and instead implement the dunder methods in your class and then use the built-in functions that call them, such as str() and repr().

What’s the difference between __str__() and __repr__()?

The __str__() method returns a human-readable, or informal, string representation of an object. This method is called by the built-in print(), str(), and format() functions. If you don’t define a __str__() method for a class, then the built-in object implementation calls the __repr__() method instead.

The __repr__() method returns a more information-rich, or official, string representation of an object. This method is called by the built-in repr() function. If possible, the string returned should be a valid Python expression that can be used to recreate the object. In all cases, the string should be informative and unambiguous.

In general, the __str__() string is intended for users and the __repr__() string is intended for developers.

__str__() and __repr__() Examples Using a Built-In Class

The examples in this section call the __str__() and __repr__() methods directly for demonstration purposes.

The datetime.datetime class is a built-in Python class which has a default implementation of the __str__() and __repr__() methods.

The following example code shows the strings returned by the default implementation of the __str__() and __repr__() methods for a datetime.datetime object:

import datetimemydate = datetime.datetime.now()print("__str__() string: ", mydate.__str__())print("str() string: ", str(mydate))print("__repr__() string: ", mydate.__repr__())print("repr() string: ", repr(mydate))

The output is:

Output

__str__() string: 2023-01-27 09:50:37.429078str() string: 2023-01-27 09:50:37.429078__repr__() string: datetime.datetime(2023, 1, 27, 9, 50, 37, 429078)repr() string: datetime.datetime(2023, 1, 27, 9, 50, 37, 429078)

The output shows that the str() function calls __str__() and returns a human-friendly string, while the repr() function calls __repr__() and returns a more information-rich string that can be used to recreate the object. In fact, you can use the repr() function with the eval() function to create a new object from the string:

import datetimemydate1 = datetime.datetime.now()mydate2 = eval(repr(mydate1))print("mydate1 repr() string: ", repr(mydate1))print("mydate2 repr() string: ", repr(mydate2))print("the values of the objects are equal: ", mydate1==mydate2)

The output is:

Output

mydate1 repr() string: datetime.datetime(2023, 1, 26, 9, 43, 24, 479635)mydate2 repr() string: datetime.datetime(2023, 1, 26, 9, 43, 24, 479635)the values of the objects are equal: True

The preceding example code creates the mydate2 object from the repr() string for mydate1, and then verifies that the values of both objects are equal.

__str__() and __repr__() Examples Using a New Class

When you create a class, you should implement at least the ___repr__() method so that useful information is returned when built-in functions use __repr__().

The following class doesn’t implement the __str__() or __repr()__ methods:

class Ocean: def __init__(self, sea_creature_name, sea_creature_age): self.name = sea_creature_name self.age = sea_creature_agec = Ocean('Jellyfish', 5)print(str(c))print(repr(c))

The output when you use str() and repr() is:

Output

<__main__.Ocean object at 0x102892860><__main__.Ocean object at 0x102892860>

The preceding example demonstrates that the default implementation of __repr()__ for the object returns a string with only the class and the object id in hexadecimal format, which is not very useful. Note that str() and repr() return the same value, because str() calls __repr__() when __str__() isn’t implemented.

Update the Ocean class with implementations of the __str__() and __repr__() methods:

class Ocean: def __init__(self, sea_creature_name, sea_creature_age): self.name = sea_creature_name self.age = sea_creature_age def __str__(self): return f'The creature type is {self.name} and the age is {self.age}' def __repr__(self): return f'Ocean(\'{self.name}\', {self.age})'c = Ocean('Jellyfish', 5)print(str(c))print(repr(c))

The output is:

Output

The creature type is Jellyfish and the age is 5Ocean('Jellyfish', 5)

The implementation of __str__() in the preceding example returns an easy-to-read string that provides the relevant details of the object for a user. The implementation of __repr__() returns a string that’s a valid Python expression which could be used to recreate the object: Ocean('Jellyfish', 5). The example uses f-string formatting for the strings, but you can format the strings using any format supported by Python.

Conclusion

In this article, you explored the differences between the __str__() and the __repr__() methods and implemented these special methods in a class, so that you didn’t need to call them directly. Learn more about working with strings in Python through our Python string tutorials.

How To Use the __str__() and __repr__() Methods in Python | DigitalOcean (2024)
Top Articles
What happens when you delete the recycle bin?
Will mortgage rates drop to 5% in 2024?
Star Wars Mongol Heleer
Golden Abyss - Chapter 5 - Lunar_Angel
Amc Near My Location
O'reilly's Auto Parts Closest To My Location
Jonathon Kinchen Net Worth
St Petersburg Craigslist Pets
Fototour verlassener Fliegerhorst Schönwald [Lost Place Brandenburg]
DIN 41612 - FCI - PDF Catalogs | Technical Documentation
3472542504
Zürich Stadion Letzigrund detailed interactive seating plan with seat & row numbers | Sitzplan Saalplan with Sitzplatz & Reihen Nummerierung
Los Angeles Craigs List
Premier Reward Token Rs3
24 Best Things To Do in Great Yarmouth Norfolk
Slope Tyrones Unblocked Games
Panic! At The Disco - Spotify Top Songs
Atdhe Net
Pirates Of The Caribbean 1 123Movies
South Bend Weather Underground
Milwaukee Nickname Crossword Clue
Ou Football Brainiacs
How do you get noble pursuit?
Astro Seek Asteroid Chart
The Ultimate Guide to Obtaining Bark in Conan Exiles: Tips and Tricks for the Best Results
NIST Special Publication (SP) 800-37 Rev. 2 (Withdrawn), Risk Management Framework for Information Systems and Organizations: A System Life Cycle Approach for Security and Privacy
Moxfield Deck Builder
Rise Meadville Reviews
Vip Lounge Odu
Covalen hiring Ai Annotator - Dutch , Finnish, Japanese , Polish , Swedish in Dublin, County Dublin, Ireland | LinkedIn
Why The Boogeyman Is Rated PG-13
Ippa 番号
The Land Book 9 Release Date 2023
AI-Powered Free Online Flashcards for Studying | Kahoot!
Los Garroberros Menu
Myanswers Com Abc Resources
Trizzle Aarp
Registrar Lls
Mugshots Journal Star
The best specialist spirits store | Spirituosengalerie Stuttgart
Hovia reveals top 4 feel-good wallpaper trends for 2024
Hkx File Compatibility Check Skyrim/Sse
Wilson Tire And Auto Service Gambrills Photos
Senior Houses For Sale Near Me
Holzer Athena Portal
Caphras Calculator
New Starfield Deep-Dive Reveals How Shattered Space DLC Will Finally Fix The Game's Biggest Combat Flaw
Jackerman Mothers Warmth Part 3
Argus Leader Obits Today
A Snowy Day In Oakland Showtimes Near Maya Pittsburg Cinemas
Sj Craigs
Peugeot-dealer Hedin Automotive: alles onder één dak | Hedin
Latest Posts
Article information

Author: Jamar Nader

Last Updated:

Views: 6225

Rating: 4.4 / 5 (55 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Jamar Nader

Birthday: 1995-02-28

Address: Apt. 536 6162 Reichel Greens, Port Zackaryside, CT 22682-9804

Phone: +9958384818317

Job: IT Representative

Hobby: Scrapbooking, Hiking, Hunting, Kite flying, Blacksmithing, Video gaming, Foraging

Introduction: My name is Jamar Nader, I am a fine, shiny, colorful, bright, nice, perfect, curious person who loves writing and wants to share my knowledge and understanding with you.