Unlock Python’s Power: A Practical Guide to Magic Methods
This article introduces Python’s magic methods, explains their purposes and usage, provides a comprehensive table of common dunder methods, and demonstrates practical examples—including object creation, attribute handling, container behavior, and context management—to help developers master these powerful language features.
Introduction
Magic methods (also known as dunder methods) are special hooks in Python that let developers customize object behavior such as creation, representation, attribute access, arithmetic operations, and context management.
Basic Magic Methods
Commonly used magic methods include:
__new__(cls, ...) : called first when an instance is created.
__init__(self, ...) : initializer called after the instance is created.
__del__(self) : destructor called when an object is garbage‑collected.
__len__(self) : defines behavior of len().
__repr__(self) and __str__(self) : define the string representation for developers and users.
__getitem__(self, key) , __setitem__(self, key, value) , __delitem__(self, key) : make an object behave like a container.
__getattr__(self, name) and __getattribute__(self, name) : control attribute access.
__enter__(self) and __exit__(self, exc_type, exc_value, traceback) : enable use of the with statement.
Commonly Used Examples
1. Object Creation and Destruction
class Student:
def __new__(cls):
print('start')
return super().__new__(cls)
def __init__(self):
self.name = '任性的90后boy'
self.age = 100
self.gender = 'female'
self.enjoy = 'do love'
print(self.age)
def __del__(self):
print(self.name)
print('end')
s = Student()
print(id(s))The output shows that __new__ runs before __init__, and __del__ is called when the object’s lifecycle ends.
2. Attribute Access Magic Methods
class Att:
def __getattribute__(self, item):
print('getattribute')
return super().__getattribute__(item)
def __getattr__(self, name):
print('getattr', name)
def __setattr__(self, name, value):
print('setattr')
super().__setattr__(name, value)
def __delattr__(self, name):
print('delattr')
super().__delattr__(name)
if __name__ == '__main__':
at = Att()
at.ab = 1
print(at.ab)
del at.abThis demonstrates how attribute reads, writes, and deletions can be intercepted.
3. Container‑Like Magic Methods
class Function:
def __init__(self, values=None):
self.values = [] if values is None else values
def __len__(self):
return len(self.values)
def __getitem__(self, key):
return self.values[key]
def __setitem__(self, key, value):
self.values[key] = value
def __delitem__(self, key):
del self.values[key]
def __iter__(self):
return iter(self.values)
def __reversed__(self):
return reversed(self.values)
# additional helper methods omitted for brevity
ff = Function([32,3,23,3,22])
print('before:', ff.__getitem__(2))
ff.__setitem__(2, 43)
print('after:', ff.__getitem__(2))The class behaves like a list, supporting indexing, iteration, and reversal.
4. Context Manager Magic Methods
class MyContext:
def __enter__(self):
print('enter')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('exit')
return False
with MyContext() as ctx:
print('inside')This shows how __enter__ and __exit__ enable custom resource management.
Conclusion
Magic methods are a fundamental part of Python’s object‑oriented design. Understanding and using them allows developers to write more expressive, concise, and Pythonic code, turning custom classes into first‑class citizens that behave like built‑in types.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
