Understanding Dunder Methods in Python: __str__ and __repr__ Methods
As an object-oriented programming language, Python revolves around the concept of objects. Virtually everything in Python, from simple data types to complex data structures, is treated as an object. These objects exhibit different behaviors, and Python provides a mechanism to define and manipulate these behaviors using special methods known as dunder (double underscore) methods or magic methods. Dunder methods, identified by their double underscores before and after the name (e.g., __str__, __repr__), play a pivotal role in defining the behavior of objects in Python. In this article, we will delve into two fundamental magic methods: __str__ and __repr__. These methods serve distinct purposes, with str defining the string representation of an object and repr specifying its printable representation. Understanding these dunder methods is crucial for effective Python programming and object-oriented design.
__str__ (string)
If you want to define a string method in a class to represent objects as strings, you can either build your own conversion method or leverage the built-in __str__ method. Let’s look at why it may be a better idea to use the built-in __str__ method than build your own. We are going to create two classes to demonstrate the difference between the two:
In this code, we have defined an instance method as a string conversion method. Notice that to use this method, we have to explicitly call it on the object (student1.my_method()). This means that the user must always remember to use this method. And just by looking at the method, one may not automatically know what it does. This adds unnecessary complications to the code. Let’s look at another example:
Here, we define an instance method using the __str__ dunder method. Notice that when we want to use the method, there is no need to explicitly call it, like in the previous example. When we print the student object (student1), the string method is invoked automatically, and we get a string representation of the object. Users of this code will easily know what the __str__ method is about, and they do not have to remember to call it every time they use the code. By using this method, we are leveraging the standard Python convention for string representation. This method is more Pythonic.
Build the Confidence to Tackle Data Analysis Projects (40% OFF)
To build a successful data analysis project, one must have skills in data cleaning and preprocessing, visualization, modeling, EDA, and so forth. The main purpose of this book is to ensure that you develop data analysis skills with Python by tackling challenges. By the end, you should be confident enough to take on any data analysis project with Python. Start your 50-day challenge now. Click here to get 40% off.
Other Resources
Want to learn Python fundamentals the easy way? Check out Master Python Fundamentals: The Ultimate Guide for Beginners.
Challenge yourself with Python challenges. Check out 50 Days of Python: A Challenge a Day.
100 Python Tips and Tricks, Python Tips and Tricks: A Collection of 100 Basic & Intermediate Tips & Tricks.
领英推荐
__repr__ (representation)
This method is also used to convert objects to strings. It works similar to the __str__ method, but it is used slightly differently. If we replace __str__ in the previous code with __repr__, we will get the same results:
You can see that the output is the same. We get the same results using __repr__ as we did using the __str__ method. However, even though the two methods have similar behavior, they are different and are used for different purposes.
The __repr__, which is called by the repr() function, is meant to return a string representation of the object that is a valid Python expression. It should ideally be unambiguous and show how the object can be recreated. Here is how this must be used in the class:
In this code, you can see that the __repr__ method is returning nothing but the object (student1) attributes: name and age. We did not add extra strings like "student name" and "gender" as in the previous examples. What __repr__ is returning is a valid expression that will recreate the object when passed to the eval() function:
Here we have used the repr() function to get the repr expression and save it to a variable called repr_string. When we pass this variable to the eval() function, it recreates the object above (Mark, male). So, this is the purpose of the __repr__ method: to return a string representation of an object that can create an object when passed to the eval() function. The information returned by the __repr__ method is not meant for the end-user; it is primarily used for debugging and development, as it provides detailed information about the object's state. On the other hand, the string information of the str method is meant for human consumption. It provides a more user-friendly and descriptive output compared to __repr__. In a Python class, you can have both the __repr__ and __str__ methods. The __repr__ will be for debugging, and the __str__ method will be for the end-user.
In this code, we have added both methods (__repr__ and __str__). Notice that while repr is giving out this unambiguous string that represents the object: Student ("Mark", "male"); the str method is being more descriptive. It is describing that "Mark" is a student name and his gender is "male."
Conclusion
So, if you want to provide string information that is more descriptive for human consumption, use the __str__ magic method. If it is for debugging, use the magic __repr__ method. If you want more tips to deepen your Python knowledge, check out "Python Tips and Tricks: A Collection of 100 Basic & Intermediate Tips & Tricks," which is now available on Amazon. Thanks for reading this article. Please like, share, and subscribe to this newsletter if you are not yet a subscriber.
Newsletter Sponsorship
You can reach a highly engaged audience of over 250,000 tech-savvy subscribers and grow your brand with a newsletter sponsorship. Contact me at [email protected] today to learn more about the sponsorship opportunities.
Business Analyst, SEO Analyst
6 个月Great article on Python magic methods! Understanding __str__ and __repr__ is crucial for writing clean and readable code. Thanks for sharing this valuable information with the community. #dataanalysis #python #learningPython
Biomedical Engineer at Kenya Medical Research Institute (KEMRI)
6 个月Very educative
Technology Enthusiast with Expertise in Python and Web Development | AI/ML Enthusiast | AWS | Developing an End-to-End Immigration Application | Actively Seeking Internship/Job Opportunities to Add Value to Companies
6 个月Thanks for sharing. Good to know about magic methods and use cases.
20+ yrs in Tech & Finance & Quant | ex-Microsoft/Oracle/CERN | IT / Cloud Architecture Leader | AI/ML Data Scientist | SaaS & Fintech
6 个月Nice, very useful. I recently made longer post on asyncio, threads, and multiprocessing in Python for investing framework. You may check at QuantJourney.substack.com