Wednesday, June 18, 2025

What built-in function calls __abs__?

All Questions From This Chapter

The built-in function abs() in Python calls the __abs__ dunder method on an object.


✅ Example:

python
class Temperature: def __init__(self, value): self.value = value def __abs__(self): return abs(self.value) temp = Temperature(-40) print(abs(temp)) # Output: 40

🔍 What’s Happening:

When you write abs(temp), Python internally calls:

python
temp.__abs__()

This allows you to define custom behavior for abs() on your own classes.


🧠 Summary:

  • abs(obj) → Calls obj.__abs__()

  • You must implement __abs__ if you want your custom class to support abs()

This is part of Python’s data model that allows operator/function overloading.

Tags: Technology,Python,Interview Preparation,

What are "dunder" methods? Give an example.

All Questions From This Chapter

"Dunder" methods (short for "double underscore" methods) are special methods in Python that begin and end with double underscores (__), like __init__, __str__, and __len__. They’re also known as magic methods or special methods.

These methods are used to:

  • Customize the behavior of built-in operations

  • Enable operator overloading

  • Integrate your class with Python's core language features (like iteration, context managers, etc.)


Example:

python
class Book: def __init__(self, title): self.title = title def __str__(self): return f"Book: {self.title}" book = Book("Fluent Python") print(book) # Output: Book: Fluent Python
  • __init__: Initializes the object (like a constructor).

  • __str__: Defines what str(obj) or print(obj) returns.


🧠 Common Dunder Methods:

MethodPurpose
__init__Constructor (called on object creation)
__str__String representation (print(obj))
__repr__Debug representation (repr(obj))
__len__Length (len(obj))
__getitem__Indexing (obj[i])
__iter__Makes an object iterable
__eq__Equality (==)

Dunder methods let your objects behave like built-in types and integrate seamlessly with Python’s syntax and idioms.

Tags: Technology,Python,Interview Preparation,

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

All Questions From This Chapter

If you don’t implement __bool__ in a Python class, Python falls back to another method to determine the truthiness of your object.

🔁 Fallback Behavior:

  1. If __bool__ is not defined, Python checks for __len__.

  2. If __len__ is defined:

    • if obj: will evaluate to False if len(obj) == 0.

    • Otherwise, it evaluates to True.

  3. If neither __bool__ nor __len__ is defined, the object is considered truthy by default (i.e., True).


🔍 Example Without __bool__:

python
class Empty: def __len__(self): return 0 e = Empty() print(bool(e)) # False, because __len__ returns 0

🧱 Example With Neither:

python
class Thing: pass t = Thing() print(bool(t)) # True, because no __bool__ or __len__

✅ Summary

You define…bool(obj) is…
__bool__Uses the returned Boolean value
__len__, no __bool__False if len(obj) == 0, True otherwise
NeitherAlways True

🧠 Tip: Define __bool__ if you want explicit control over an object’s truthiness.

Tags: Technology,Python,Interview Preparation,

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,