Fundamentals 5 min read

Understanding Python Magic Methods: __bool__, __int__, __float__, __complex__, __index__, __oct__, __hex__, and __dir__

This article explains Python's special (magic) methods such as __bool__, __int__, __float__, __complex__, __index__, __oct__, __hex__, and __dir__, describing their purpose, how they affect object behavior, and provides concrete code examples demonstrating their usage and output.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Understanding Python Magic Methods: __bool__, __int__, __float__, __complex__, __index__, __oct__, __hex__, and __dir__

Python provides a set of special methods, often called magic methods, that allow objects to define their behavior for built‑in operations such as truth testing, numeric conversion, indexing, and introspection.

__bool__ determines whether an instance is considered True or False . By default any non‑empty object is True , but defining __bool__ lets you customize this logic.

__int__ , __float__ and __complex__ are used to convert an object to an int , float or complex value respectively, which is useful for numeric‑oriented custom classes.

__index__ is similar to __int__ but is specifically invoked for slicing and indexing operations; in Python 3 it replaces __int__ for those contexts.

__oct__ and __hex__ return the octal and hexadecimal string representations of an integer‑like object.

__dir__ returns a list of attribute names for the object and is called by the built‑in dir() function.

Below is a sample class that implements all of these methods:

class Number:
    def __init__(self, value):
        self.value = value
    def __bool__(self):
        return self.value != 0
    def __int__(self):
        return int(self.value)
    def __float__(self):
        return float(self.value)
    def __complex__(self):
        return complex(self.value)
    def __index__(self):
        return int(self.value)
    def __oct__(self):
        return oct(int(self.value))
    def __hex__(self):
        return hex(int(self.value))
    def __dir__(self):
        return ['value']

Typical usage examples:

n1 = Number(0)
print(bool(n1))   # False
n2 = Number(10)
print(bool(n2))   # True
print(int(n2))    # 10
print(float(n2))  # 10.0
print(complex(n2))# (10+0j)
print([1, 2, 3][n2]) # 3
print(oct(n2))    # 0o12
print(hex(n2))    # 0xa
print(dir(n2))    # ['value']

Additional examples show how a Fraction class can implement __int__ , __float__ , __complex__ and __index__ to provide meaningful numeric conversions:

class Fraction:
    def __init__(self, numerator, denominator):
        self.numerator = numerator
        self.denominator = denominator
    def __int__(self):
        return self.numerator // self.denominator
    def __float__(self):
        return self.numerator / self.denominator
    def __complex__(self):
        return complex(self.numerator, self.denominator)
    def __index__(self):
        return self.numerator // self.denominator

f1 = Fraction(3, 2)
print(int(f1))   # 1
print(float(f1)) # 1.5
f2 = Fraction(1, 2)
print(complex(f2)) # (0.5+0j)

When running the code, ensure you are using Python 3.x, as the behavior of some magic methods (especially __index__ ) differs from earlier versions.

PythonintSpecial Methodscode-examplesMagic Methodsbool
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.