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
7 Pros & 3 Cons Of Wholesaling Real Estate
Are Ethereum’s smart contracts better than its competitors?
Katie Pavlich Bikini Photos
My E Chart Elliot
Combat level
Ixl Elmoreco.com
Gabriel Kuhn Y Daniel Perry Video
South Park Season 26 Kisscartoon
Air Canada bullish about its prospects as recovery gains steam
Mr Tire Prince Frederick Md 20678
Sportsman Warehouse Cda
Graveguard Set Bloodborne
Mivf Mdcalc
Shooting Games Multiplayer Unblocked
Diablo 3 Metascore
Identogo Brunswick Ga
Uhcs Patient Wallet
Top tips for getting around Buenos Aires
24 Hour Walmart Detroit Mi
Studentvue Columbia Heights
Sony E 18-200mm F3.5-6.3 OSS LE Review
Curtains - Cheap Ready Made Curtains - Deconovo UK
Whitefish Bay Calendar
Craigslist Southern Oregon Coast
Mychart Anmed Health Login
Apple Original Films and Skydance Animation’s highly anticipated “Luck” to premiere globally on Apple TV+ on Friday, August 5
Sullivan County Image Mate
The Tower and Major Arcana Tarot Combinations: What They Mean - Eclectic Witchcraft
Teekay Vop
Jeff Nippard Push Pull Program Pdf
Chime Ssi Payment 2023
Watson 853 White Oval
Truvy Back Office Login
Gillette Craigslist
Taylored Services Hardeeville Sc
Emuaid Max First Aid Ointment 2 Ounce Fake Review Analysis
Winterset Rants And Raves
The value of R in SI units is _____?
Human Unitec International Inc (HMNU) Stock Price History Chart & Technical Analysis Graph - TipRanks.com
Envy Nails Snoqualmie
Skyrim:Elder Knowledge - The Unofficial Elder Scrolls Pages (UESP)
Can You Buy Pedialyte On Food Stamps
Tugboat Information
3496 W Little League Dr San Bernardino Ca 92407
Birmingham City Schools Clever Login
Bill Manser Net Worth
Anthem Bcbs Otc Catalog 2022
My Eschedule Greatpeople Me
Reli Stocktwits
Diesel Technician/Mechanic III - Entry Level - transportation - job employment - craigslist
Southern Blotting: Principle, Steps, Applications | Microbe Online
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.