In this lesson, you will learn how to make your custom objects "speak the language" of Python’s built-in conversion functions by implementing special dunder methods.
Making Objects Compatible with Built-ins
When you pass an object to functions like int(), float(), or abs(), Python looks for specific dunder methods defined within that object's class. By implementing these methods, you allow your custom types to integrate seamlessly into existing Python logic without needing to call a custom .convert() or .value() method every time.
For example, if you are building a Quantity class that represents a measurement, you might want to convert it directly to an integer or a float.
The Conversion Methods
__int__(self): Triggered when you callint(obj).__float__(self): Triggered when you callfloat(obj).__abs__(self): Triggered when you callabs(obj).
Consider this Vector class representing a magnitude:
class Magnitude:
def __init__(self, value):
self.value = value
def __abs__(self):
return abs(self.value)
def __int__(self):
return int(self.value)
def __float__(self):
return float(self.value)
# Usage
m = Magnitude(-5.75)
print(abs(m)) # Output: 5.75
print(int(m)) # Output: -5
print(float(m)) # Output: -5.75
By defining these methods, your object behaves exactly like a native numeric type in these contexts. You aren't just creating a container for data; you are creating an object that understands how to translate its internal state into the standardized formats that Python's built-in math and conversion functions expect.
This approach keeps your API clean—instead of asking a user to call my_obj.to_int(), you allow them to use the standard, idiomatic int(my_obj). This makes your code more predictable and easier for other developers to integrate into their own projects.
Key Takeaway: Implement __int__, __float__, and __abs__ to allow your custom objects to integrate natively with Python’s built-in conversion and mathematical functions.