Unlock Python’s Power: Master Magic Methods for Advanced Object Behavior
This article explains Python’s magic methods—special double‑underscore functions like __init__, __new__, __getattr__, and __call__—showing how they control object construction, attribute access, custom containers, callability, context management, descriptors, and copying, with clear code examples for each feature.
Introduction
In Python, any method whose name is surrounded by double underscores (e.g., __init__) is called a magic method. These methods let developers customize object creation, attribute handling, container behavior, and more.
Construction and Initialization
Besides the familiar __init__ constructor, Python calls __new__ first to create an instance, then __init__ to initialise it. When an object’s lifecycle ends, __del__ acts as a destructor.
from os.path import join
class FileObject:
"""Wrap a file object and ensure the file stream is closed on deletion."""
def __init__(self, filepath='~', filename='sample.txt'):
# open file in read‑write mode
self.file = open(join(filepath, filename), 'r+')
def __del__(self):
self.file.close()
del self.fileControlling Attribute Access
Python lets you intercept attribute operations with magic methods: __getattr__(self, name) – called when an attribute is not found. __setattr__(self, name, value) – called for every attribute assignment; avoid infinite recursion by assigning to self.__dict__[name]. __delattr__(self, name) – called when an attribute is deleted. __getattribute__(self, name) – called for *all* attribute accesses; rarely overridden because it is easy to introduce bugs.
# Incorrect implementation – causes infinite recursion
def __setattr__(self, name, value):
self.name = value # triggers __setattr__ again
# Correct implementation
def __setattr__(self, name, value):
self.__dict__[name] = valueCreating Custom Containers
To make a class behave like built‑in containers, implement the container protocol methods:
__len__(self) __getitem__(self, key) __setitem__(self, key, value) __delitem__(self, key) __iter__(self) __reversed__(self) __contains__(self, item) __missing__(self, key)– used by dict subclasses.
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)Example: FunctionalList
class FunctionalList:
"""Imitates built‑in list and adds head, tail, init, last, drop, take methods."""
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 FunctionalList(reversed(self.values))
def append(self, value):
self.values.append(value)
def head(self):
return self.values[0]
def tail(self):
return self.values[1:]
def init(self):
return self.values[:-1]
def last(self):
return self.values[-1]
def drop(self, n):
return self.values[n:]
def take(self, n):
return self.values[:n]Reflection
Customise isinstance() and issubclass() checks with:
def __instancecheck__(self, instance):
...
def __subclasscheck__(self, subclass):
...Callable Objects
Implement __call__ so an instance behaves like a function.
class Entity:
"""An object that can be called to change its position."""
def __init__(self, size, x, y):
self.x, self.y = x, y
self.size = size
def __call__(self, x, y):
"""Change the entity’s position."""
self.x, self.y = x, yContext Management
With‑statement support requires __enter__ and __exit__ methods.
def __enter__(self):
...
def __exit__(self, exc_type, exc_val, exc_tb):
...Descriptors
Descriptors define managed attribute access via __get__, __set__, and __delete__. Example converting between metres and feet:
class Meter:
def __init__(self, value=0.0):
self.value = float(value)
def __get__(self, instance, owner):
return self.value
def __set__(self, instance, value):
self.value = float(value)
class Foot:
def __get__(self, instance, owner):
return instance.meter * 3.2808
def __set__(self, instance, value):
instance.meter = float(value) / 3.2808
class Distance:
meter = Meter(10)
foot = Foot()Usage:
>> d = Distance()
>>> print(d.foot)
32.808
>>> print(d.meter)
10.0Copy
Control shallow and deep copying with __copy__ and __deepcopy__.
def __copy__(self):
... # return shallow copy
def __deepcopy__(self, memo):
... # return deep copyAppendix
Tables summarising comparison and numeric‑operation magic methods:
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.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
