Custom Classes: A Complete Guide to Python Magic Methods
In Python, double underscore__Beginning and ending methods (e.g.__init__、__str__) are called magic methods (or special methods). They are the core of Python class customization, allowing our custom types to behave as naturally as built-in types (such as lists and strings). This article will sort out the usage of common magic methods and use examples to help you master the skills of class customization.
1. Object representation method: let the instance "speak"
When we print an object or view it in an interactive environment, Python calls special methods to generate a string representation. The most commonly used is__str__and__repr__。
✨ __str__and__repr__
Usage Example:
💡 Best Practices
__repr__Information about the reconstructed object should be included where possible (e.g.Student(name='张三')Can be copied and run directly);- If only one is implemented, give priority
__repr__——__str__Will automatically fall back to when undefined__repr__。
2. Iterator protocol: Make instances "loopable"
Want the object to beforLoop traversal needs to be implemented__iter__and__next__Two methods, this is the iterator protocol.
🔄 __iter__and__next__
Take the Fibonacci sequence generator as an example:
Usage Example:
3. Sequence protocol: Let the instance "support subscript access"
If you want to use the object like a list[]Access (including indexing and slicing) needs to be implemented__getitem__; If you want to support modifying or deleting elements, you can continue to implement__setitem__and__delitem__。
🔢 __getitem__Example
Add subscript access functions to the Fibonacci class:
Usage Example:
You can also add__len__methods to supportlen()function:
4. Attribute access control: dynamic processing of attributes
When accessing or setting a property of an object that does not exist, Python calls__getattr__and__setattr__, can be used to implement dynamic attribute management.
🧩 __getattr__and__setattr__
Usage Example:
5. Callable objects: Make instances "like functions"
accomplish__call__After the method, instances of the class can be called like functions, which is very useful in "functions" that need to save state.
📞 __call__Example
Make a prefixed logger:
Usage Example:
6. Context manager: let the instance "support the with statement"
withStatements can automatically manage resources (such as opening/closing files). For classes to support it, they need to be implemented__enter__and__exit__。
🧹 __enter__and__exit__Example
Simulate a resource management class:
Usage Example:
7. New practical magic methods in Python 3.x
🔡 __bytes__: Define the behavior of converting byte sequences
🎨 __format__: Custom formatted output
🧬 __class_getitem__(3.7+): Support generic type hints
Simply put, it allows a class likelist[int]The same is used for type annotations, such as:
Best Practices
- Maintain consistency: The behavior of magic methods must be aligned with built-in types (such as
__len__Must return a non-negative integer); - ** Priority implementation
__repr__**: It is the "official" representation of the object and can override__str__the absence of; - Avoid
__getattribute__Abuse: All attribute access will trigger it, which can easily lead to recursion and should not be used unless necessary; - Performance first: Magic methods are often called implicitly (such as in loops
__next__), to ensure high efficiency.
Summarize
Python's magic methods are like a set of "hooks" that allow us to seamlessly customize the behavior of a class. From string representation to iteration, from attribute management to context management, mastering these methods will help you write more concise and Python-style code. If you want to know all the magic methods, you can refer to 官方文档.

