Understanding Python Magic Methods
Ohidur Rahman Bappy
MAR 22, 2025
Understanding Python Magic Methods
Python magic methods, often known as dunder methods (short for 'double underscore'), offer a powerful way to leverage object-oriented programming to the fullest. They allow classes to implement and customize specific behaviors for built-in operations. Below is a complete example of some key magic methods in Python.
FileObject Class
The FileObject
class demonstrates the use of __init__
and __del__
magic methods to ensure that a file is properly opened and closed.
from os.path import join
class FileObject:
"""Wrapper for file objects to make sure the file gets closed on deletion."""
def __init__(self, filepath="~", filename="sample.txt"):
# Open a file in read and write mode
self.file = open(join(filepath, filename), "r+")
def __del__(self):
self.file.close()
del self.file
Word Class
The Word
class uses __new__
for immutability and defines comparison methods for word lengths.
class Word(str):
"""Class for words, defining comparison based on word length."""
def __new__(cls, word):
if " " in word:
print "Value contains spaces. Truncating to first space."
word = word[:word.index(" ")]
return str.__new__(cls, word)
def __gt__(self, other):
return len(self) > len(other)
def __lt__(self, other):
return len(self) < len(other)
def __ge__(self, other):
return len(self) >= len(other)
def __le__(self, other):
return len(self) <= len(other)
AccessCounter Class
The AccessCounter
demonstrates how to track changes to an attribute using __setattr__
and __delattr__
.
class AccessCounter:
"""A class that contains a value and implements an access counter."""
def __init__(self, val):
self.__dict__["counter"] = 0
self.__dict__["value"] = val
def __setattr__(self, name, value):
if name == "value":
self.__dict__["counter"] += 1
self.__dict__["value"] = value
def __delattr__(self, name):
if name == "value":
self.__dict__["counter"] += 1
del self.__dict__["value"]
FunctionalList Class
This class wraps a list and demonstrates several methods, such as __len__
, __getitem__
, and others.
class FunctionalList:
"""A class wrapping a list with some extra functional magic."""
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)
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]
Entity Class
The Entity
class can be called as a function to update its position.
class Entity:
"""Class to represent an entity. Callable to update the entity's position."""
def __init__(self, size, x, y):
self.x, self.y = x, y
self.size = size
def __call__(self, x, y):
self.x, self.y = x, y
Closer Class
A context manager class that ensures an object is closed with a with
statement.
class Closer:
"""A context manager to automatically close an object in a with statement."""
def __init__(self, obj):
self.obj = obj
def __enter__(self):
return self.obj
def __exit__(self, exception_type, exception_val, trace):
try:
self.obj.close()
except AttributeError:
print "Not closable."
return True
Using Descriptors
The Meter
and Foot
classes demonstrate descriptors in action.
class Meter(object):
"""Descriptor for a 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(object):
"""Descriptor for a foot."""
def __get__(self, instance, owner):
return instance.meter * 3.2808
def __set__(self, instance, value):
instance.meter = float(value) / 3.2808
class Distance(object):
"""Class to represent distance holding descriptors for meters and feet."""
meter = Meter()
foot = Foot()
Slate Class
This class illustrates controlling the pickling process.
import time
class Slate:
"""Class that stores a string and a changelog, forgetting its value when pickled."""
def __init__(self, value):
self.value = value
self.last_change = time.asctime()
self.history = {}
def change(self, new_value):
self.history[self.last_change] = self.value
self.value = new_value
self.last_change = time.asctime()
def print_changes(self):
print "Changelog for Slate object:"
for k, v in self.history.items():
print "%s\t %s" % (k, v)
def __getstate__(self):
return self.history
def __setstate__(self, state):
self.history = state
self.value, self.last_change = None, None
This comprehensive guide dives deep into the various magic methods in Python, providing you with a toolkit to tweak and extend Python's behavior effectively.