Fundamentals 7 min read

10 Most Common Python Magic Methods with Practical Examples

This article introduces ten of the most frequently used Python magic (dunder) methods, explains their purpose, and provides clear code examples for __init__, __str__, __repr__, __add__, __len__, __getitem__, __setitem__, __iter__, __next__, __call__, __enter__, __exit__, __getattr__, __setattr__, and __new__, helping readers master Python’s special syntax.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
10 Most Common Python Magic Methods with Practical Examples

In Python, magic methods (also called dunder methods) are special member functions that enable custom behavior for built‑in operations. This guide explores ten of the most useful magic methods, illustrating each with concise, runnable code.

Example 1: __init__ (constructor) – Called automatically when a class instance is created to initialize its state.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person = Person("张三", 30)
print(person.name)  # 输出:张三

Example 2: __str__ and __repr__ – Provide string representations; __str__ is user‑friendly, __repr__ is for debugging.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __str__(self):
        return f"{self.name} ({self.age}岁)"
    def __repr__(self):
        return f"Person('{self.name}', {self.age})"

person = Person("李四", 25)
print(str(person))   # 输出:李四 (25岁)
print(repr(person))  # 输出:Person('李四', 25)

Example 3: __add__ (operator overloading) – Allows the + operator to work with custom objects.

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

v1 = Vector(1, 2)
v2 = Vector(3, 4)
v3 = v1 + v2
print(v3.x, v3.y)  # 输出:4 6

Example 4: __len__ – Enables the built‑in len() function to return the length of an object.

class MyList:
    def __init__(self, items):
        self.items = items
    def __len__(self):
        return len(self.items)

my_list = MyList([1, 2, 3])
print(len(my_list))  # 输出:3

Example 5: __getitem__ and __setitem__ (indexing) – Customize how objects respond to indexing and assignment.

class MyList:
    def __init__(self, items):
        self.items = items
    def __getitem__(self, index):
        return self.items[index]
    def __setitem__(self, index, value):
        self.items[index] = value

my_list = MyList([1, 2, 3])
print(my_list[0])   # 输出:1
my_list[0] = 10
print(my_list[0])   # 输出:10

Example 6: __iter__ and __next__ (iterator protocol) – Define how an object can be iterated over.

class Counter:
    def __init__(self, max):
        self.max = max
        self.current = 0
    def __iter__(self):
        return self
    def __next__(self):
        if self.current >= self.max:
            raise StopIteration
        self.current += 1
        return self.current - 1

for i in Counter(5):
    print(i)  # 输出:0, 1, 2, 3, 4

Example 7: __call__ – Makes an instance behave like a function.

class Callable:
    def __call__(self, x):
        return x * 2

func = Callable()
print(func(5))  # 输出:10

Example 8: __enter__ and __exit__ (context manager) – Implement the with‑statement protocol.

class MyFile:
    def __init__(self, filename):
        self.filename = filename
    def __enter__(self):
        self.file = open(self.filename, 'r')
        return self.file
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.file.close()

with MyFile('example.txt') as file:
    content = file.read()
    print(content)

Example 9: __getattr__ and __setattr__ (dynamic attributes) – Control attribute access and assignment.

class Dynamic:
    def __getattr__(self, name):
        return f"动态获取属性 {name}"
    def __setattr__(self, name, value):
        print(f"设置属性 {name} 为 {value}")
        super().__setattr__(name, value)

dynamic = Dynamic()
print(dynamic.some_attribute)  # 输出:动态获取属性 some_attribute
dynamic.some_attribute = "新的值"

Example 10: __new__ (singleton pattern) – Called before __init__, can enforce a single instance.

class Singleton:
    _instance = None
    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

s1 = Singleton()
s2 = Singleton()
print(s1 is s2)  # 输出:True

These magic methods make Python classes and objects more powerful and flexible. Mastering them gives you deeper insight into Python’s core capabilities.

If you have questions or want more details, feel free to comment or message, and subscribe to the WeChat channel for future programming tips.

programmingOOPexamplesMagic MethodsDunder
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.