Wednesday, June 18, 2025

What is the difference between __repr__ and __str__?

All Questions From This Chapter

__repr__ and __str__

In Python, __repr__ and __str__ are both special methods used to define how an object is represented as a string, but they serve different purposes:


__repr__: Developer-Friendly Representation

  • Goal: Provide an unambiguous string representation of the object.

  • Should ideally return a string that could be used to recreate the object.

  • Used by:

    • repr(obj)

    • Interactive console

    • Debugging and logging

Example:

python
class Book: def __init__(self, title): self.title = title def __repr__(self): return f"Book('{self.title}')"

__str__: User-Friendly Representation

  • Goal: Provide a readable or nicely formatted string for end users.

  • Used by:

    • str(obj)

    • print(obj)

Example:

python
class Book: def __init__(self, title): self.title = title def __str__(self): return f"Book title: {self.title}"

💡 If Only __repr__ is Defined?

If you only define __repr__, str(obj) and print(obj) will fall back to using __repr__.


🧠 Summary:

MethodPurposeUsed ByReturn Style
__repr__Developer/debug outputrepr(), consolePrecise, evaluatable
__str__User-facing outputstr(), print()Readable, informal

Best practice: Always define __repr__. Define __str__ if you want user-friendly output.

Tags: Python,Interview Preparation,Technology,

How can you make an object iterable in Python?

All Questions From This Chapter

Make an object iterable

To make an object iterable in Python, you need to implement either:


✅ Option 1: __iter__()

The simplest and most common way is to define an __iter__() method that returns an iterator (usually self or a generator).

Example:

python
class MyIterable: def __init__(self, data): self.data = data def __iter__(self): return iter(self.data) # delegates to the iterable data obj = MyIterable([1, 2, 3]) for item in obj: print(item)

✅ Option 2: __getitem__() (legacy approach)

If your object implements __getitem__() and raises IndexError when the sequence ends, it is implicitly iterable.

Example:

python
class MyIterable: def __init__(self, data): self.data = data def __getitem__(self, index): return self.data[index] obj = MyIterable([10, 20, 30]) for item in obj: print(item)

Python internally tries to call obj[0], obj[1], ... until IndexError is raised.


🧠 Summary:

MethodRequired?Purpose
__iter__()YesReturns an iterator for your object
__next__()OptionalNeeded if your class is also the iterator
__getitem__()LegacyAllows iteration without __iter__()

Best practice: Prefer __iter__() + generators for clean, efficient code.

Tags: Python,Interview Preparation,Technology,

How does __getitem__ enable sequence-like behavior in a class?

All Questions From This Chapter

__getitem__ to enable sequence-like behavior

The __getitem__ method enables sequence-like behavior in a Python class by allowing you to access items in the object using square bracket notation—just like you do with lists, tuples, or strings.


✅ What it does:

When you define __getitem__(self, key) in your class:

  • Python calls this method whenever you do obj[key]

  • You can support:

    • Indexing (obj[0])

    • Slicing (obj[1:4])

    • Even complex keys like tuples (obj[1, 2])


📦 Example:

python
class MySequence: def __init__(self, data): self.data = data def __getitem__(self, index): return self.data[index] seq = MySequence([10, 20, 30, 40]) print(seq[1]) # 20 print(seq[1:3]) # [20, 30]

🔁 What it enables:

  • Looping with for item in obj

  • Indexing and slicing

  • Compatibility with len(), in, enumerate(), etc. (if other methods like __len__ and __iter__ are also defined)


🧠 Summary:

Implementing __getitem__ turns your class into an indexable and iterable object, giving it familiar behavior like Python’s built-in sequences.

Tags: Technology,Python,Interview Preparation,

What is the purpose of __len__ in a Python class?

All Questions From This Chapter

__len__ in a Python class?

The purpose of __len__ in a Python class is to define how the built-in len() function should behave when called on an instance of that class.

Why it's used:

  • When you implement __len__, you're telling Python how to compute the "length" of your custom object.

Example:

python
class MyCollection: def __init__(self, items): self.items = items def __len__(self): return len(self.items) c = MyCollection([1, 2, 3]) print(len(c)) # Output: 3

Key Points:

  • __len__ must return an integer ≥ 0.

  • If __len__ is not defined, calling len() on the object will raise a TypeError.

It’s especially useful when creating custom container types that conceptually hold multiple items.

Tags: Python,Interview Preparation,Technology,

Interview Questions on "The Python Data Model" - Ch 1 - Fluent Python

All Posts on Python

Easy Questions

  1. What is the Python Data Model?

  2. Why does Python use len(collection) instead of collection.len()?
    Why is `len()` not a method in Python?

  3. What are "dunder" methods? Give an example.

  4. What is the purpose of __len__ in a Python class?

  5. How does __getitem__ enable sequence-like behavior in a class?

  6. What is the difference between __repr__ and __str__?

  7. Why is __repr__ important for debugging?

  8. How can you make an object iterable in Python?

  9. What happens if you don’t implement __bool__ in a class?

  10. What built-in function calls __abs__?


Medium Questions

  1. Explain how FrenchDeck leverages the Python Data Model to support slicing and iteration.

  2. Why does random.choice work on FrenchDeck without any extra methods?

  3. How does __contains__ affect the behavior of the in operator?

  4. What is the role of collections.namedtuple in the FrenchDeck example?

  5. How would you modify FrenchDeck to make it shuffleable?

  6. Why should you avoid directly calling special methods like __len__?

  7. How does __add__ enable vector addition in the Vector class?

  8. Why does Vector.__bool__ check bool(abs(self)) instead of just self.x or self.y?

  9. What is the difference between __mul__ and __rmul__?

  10. How does Python determine the truth value of an object if __bool__ is not implemented?


Complex Questions

  1. How does Python’s handling of len() differ for built-in types vs. custom classes?

  2. Explain the concept of the "metaobject protocol" in Python.

  3. Why does the Vector class return a new instance in __add__ and __mul__ instead of modifying self?

  4. How could you extend the Vector class to support n-dimensional vectors?

  5. Discuss the trade-offs between using abs(self) vs. self.x or self.y in Vector.__bool__.

  6. What are "reversed operators" (e.g., __radd__), and when are they used?

  7. How does Python’s operator overloading compare to other languages like C++ or Java?

  8. Why does the Python Data Model avoid arbitrary "magic" method names like __foo__?

  9. How could you implement a context manager using __enter__ and __exit__?

  10. What are the performance implications of using special methods vs. direct method calls?


These questions cover fundamental concepts, practical implementations, and deeper design principles from the chapter, suitable for assessing a candidate’s understanding of Python’s Data Model.

Generated using DeepSeek (R1) from the chapter 1 of book "Fluent Python" by Luciano Ramalho Tags: Technology,Python,Interview Preparation,