❔ Interview Question
What is the difference between
tags: #interview #python #magicmethods #classes
➡️ @DataScienceQ 🤎
What is the difference between
__str__ and __repr__ methods in Python classes, and when would you implementstr__str__ returns a human-readable string representation of an object (e.g., via print(obj)), making it user-friendly for displayrepr__repr__ aims for a more detailed, unambiguous string that's ideally executable as code (like repr(obj)), useful for debugging—imstr __str__ for end-user outrepr__repr__ for developer tools or str __str__ is defined.tags: #interview #python #magicmethods #classes
Please open Telegram to view this post
VIEW IN TELEGRAM
In Python, "Magic Methods" (also known as Dunder methods, short for "double underscore") are special methods that allow you to define how objects of your class behave with built-in functions and operators. While
Output:
#Python #MagicMethods #DunderMethods #OOP #Classes #PythonTips #CodeExamples #StringRepresentation #ObjectOrientation #Programming
---
By: @DataScienceQ ✨
init handles object initialization, str and repr are crucial for defining an object's string representation.str: Returns a "user-friendly" string representation of an object, primarily for human readability (e.g., when print() is called).repr: Returns an "official" string representation of an object, primarily for developers, often aiming to be unambiguous and allow recreation of the object.class Book:
def init(self, title, author, year):
self.title = title
self.author = author
self.year = year
def str(self):
return f'"{self.title}" by {self.author} ({self.year})'
def repr(self):
return f"Book('{self.title}', '{self.author}', {self.year})"
Creating an instance
my_book = Book("The Hitchhiker's Guide to the Galaxy", "Douglas Adams", 1979)
str is used by print()
print(my_book)
repr is used by the interpreter or explicitly with repr()
print(repr(my_book))
In collections, repr is used by default
bookshelf = [my_book, Book("Pride and Prejudice", "Jane Austen", 1813)]
print(bookshelf)
Output:
"The Hitchhiker's Guide to the Galaxy" by Douglas Adams (1979)
Book('The Hitchhiker\'s Guide to the Galaxy', 'Douglas Adams', 1979)
[Book('The Hitchhiker\'s Guide to the Galaxy', 'Douglas Adams', 1979), Book('Pride and Prejudice', 'Jane Austen', 1813)]
#Python #MagicMethods #DunderMethods #OOP #Classes #PythonTips #CodeExamples #StringRepresentation #ObjectOrientation #Programming
---
By: @DataScienceQ ✨