Fundamentals 14 min read

Understanding Python Magic (Dunder) Methods

This article explains Python's built‑in magic (dunder) methods—functions that start and end with double underscores—showing how they enable custom class behavior such as indexing, iteration, string representation, callable objects, context management, object creation, and attribute handling with clear code examples.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Understanding Python Magic (Dunder) Methods

Magic methods (also called dunder methods) are special functions in Python that begin and end with double underscores, allowing developers to customize the behavior of user‑defined classes.

Common examples include:

__getitem__ – enables indexing and makes a class iterable.

__len__ – returns the length of an object.

__str__ and __repr__ – control string representations for end‑users and developers.

__call__ – makes an instance behave like a function.

__enter__ and __exit__ – implement context‑manager protocols for use with with statements.

__new__ and __init__ – manage object creation and initialization, especially for immutable types.

Attribute‑related methods such as __getattr__ , __setattr__ , __getattribute__ , and descriptor methods __get__ , __set__ , __delete__ .

Below are representative code snippets illustrating each concept.

Example of __getitem__ and iteration:

class magic:
    def __init__(self, num):
        self.num = num

    def __getitem__(self, item):
        return self.num[item]

a = magic(['1', '2', '3'])
for x in a:
    print(x)

Result:

1
2
3

Example of __len__ and custom length:

class magic:
    '''This is a functional docstring.
    Use __doc__ to view it.'''
    def __init__(self, num):
        self.num = num
    def __len__(self):
        return 6666666

a = magic(5)
print(len(a))
print(a.__doc__)

Result:

6666666
This is a functional docstring.
Use __doc__ to view it.

String representation with __str__ :

class magic:
    def __init__(self, num):
        self.num = num
    def __str__(self):
        return (self.num + '\n') * 5

a = magic('浪子好帅啊')
print(a)

Result (each line printed five times):

浪子好帅啊
浪子好帅啊
浪子好帅啊
浪子好帅啊
浪子好帅啊

Making an instance callable with __call__ :

class magic:
    def __init__(self):
        pass
    def __call__(self, num):
        return '浪子:' + num

a = magic()
print(a('admin'))

Result:

浪子:admin

Context‑manager implementation using __enter__ and __exit__ :

class magic:
    def __enter__(self):
        print('enter魔法函数执行')
        return 'enter魔法函数执行完毕'
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('exti魔法函数执行')
        return 'exit魔法函数执行完毕'

def ma():
    return magic()

with ma() as a:
    print('随便执行一些东西')

Result:

enter魔法函数执行
随便执行一些东西
exti魔法函数执行

Object creation order with __new__ and __init__ :

class magic(object):
    def __new__(cls, nums):
        cls.nums = nums
        print('new:' + cls.nums)
        return object.__new__(cls)
    def __init__(self, nums):
        self.nums = nums
        print('666')
        print('init:' + self.nums)

a = magic('A')

Result:

new:A
666
init:A

These examples demonstrate how magic methods provide a powerful, flexible way to extend Python's object model and build custom, expressive data types.

iteratorsObject-Oriented ProgrammingContext ManagersMagic MethodsDunderCallable Objects
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

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.