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,

No comments:

Post a Comment