Unlock Python’s Magic Methods: A Practical Guide to Special Attributes
This article explains Python’s special attributes and magic methods—including __hash__, __eq__, __bool__, __repr__, __str__, and context management—showing how they affect object behavior, hashing, equality, truth testing, representation, and resource handling with clear code examples.
Special Attributes
Attribute
Meaning
__name__
Name of class, function, or method
__module__
Module where the class is defined
__class__
Class to which an object or class belongs
__bases__
Tuple of base classes
__doc__
Docstring of class or function (None if not defined)
__mro__
Method resolution order (class.mro())
__dict__
Writable dictionary of attributes for a class or instance
__dir__
List of member names; called by dir()
Magic Methods
Categories
Creation, initialization and destruction (__init__, __del__)
Hashing (__hash__)
Boolean evaluation (__bool__)
Visualization (__repr__, __str__, __bytes__)
Operator overloading
Container size and length
Callable objects (__call__)
Context management (__enter__, __exit__)
Reflection (__getattr__, __getattribute__, etc.)
__hash__
The hash() function returns an integer; defining __hash__ makes instances hashable.
class A:
def __init__(self, name, age=18):
self.name = name
self.age = age
def __hash__(self):
return 1
def __repr__(self):
return self.name
print(hash(A('tom')))
print((A('tom'), A('tom')))
print({A('tom'), A('tom')})
print({A('tom'): 1, A('tom'): 2})
print({A('tom'), A('tom')})
print({tuple('t'), tuple('t')})
print({('tom',), ('tom',)})
print({'tom', 'tom'})This example shows that equal hash values do not guarantee object equality; hash collisions can occur. To remove duplicate keys from a set, you must also implement __eq__.
class A:
def __init__(self, name, age=18):
self.name = name
self.age = age
def __hash__(self):
return 1
def __eq__(self, other):
return self.name == other.name
def __repr__(self):
return self.name
print({A('tom'), A('tom')})__eq__
Corresponds to the == operator; returns a bool indicating whether two objects are equal.
Comparison with __hash__:
__hash__ only provides a hash value for use as a set or dict key; __eq__ is needed to decide actual equality.
Equal hash values may be a collision and do not imply equality.
Providing __hash__ alone is usually for using the object as a key.
Non‑hashable objects return False for isinstance(obj, collections.Hashable).
__bool__
The built‑in bool() calls __bool__; if not defined, Python falls back to __len__ (non‑zero is True). If __len__ is also missing, all instances are considered True.
Visualization Magic Methods
__repr__
repr() returns the official string representation of an object; if __repr__ is not defined, the default shows the object's memory address.
__str__
str() (and print/format) use __str__ if defined; otherwise they fall back to __repr__.
__bytes__
bytes() returns a bytes representation of the object.
class A:
def __init__(self, name, age=18):
self.name = name
self.age = age
def __repr__(self):
return 'repr:{},{}'.format(self.name, self.age)
def __str__(self):
return 'str: {},{}'.format(self.name, self.age)
def __bytes__(self):
import json
return json.dumps(self.__dict__).encode()
print(A('tom'))
print([A('tom')])
print([str(A('tom'))])Operator Overloading
Operator
Special Method
Meaning
<, <=, ==, >, >=, !=
__lt__, __le__, __eq__, __gt__, __ge__, __ne__
Comparison operators
+, -, *, /, %, **, divmod
__add__, __sub__, __mul__, __truediv__, __mod__, __floordiv__, __pow__, __divmod__
Arithmetic operators (including shift and bitwise)
@functools.total_ordering decorator
Implements the full set of ordering methods from a minimal subset, but should be used sparingly.
Container‑Related Methods
Method
Meaning
__len__
len() returns the size; also used by bool() when __bool__ is missing.
__iter__
Returns an iterator for iteration.
__contains__
Implements the in operator; falls back to __iter__ if absent.
__getitem__
Enables self[key] access; raises KeyError if key not found.
__setitem__
Sets a value for self[key].
__missing__
Called by dict subclasses when a key is absent.
Callable Objects
In Python everything is an object, including functions; calling a function actually invokes its __call__ method.
Context Management
If a class implements both __enter__() and __exit__(), its instances can be used with the with statement.
class Point:
def __init__(self):
print('init')
def __enter__(self):
print('enter')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('exit')
return True # suppress exceptions
with Point() as p:
print('do something')__enter__ returns the object bound after as; __exit__ receives exception information and can suppress it by returning a true value.
Parameters
__enter__ takes no arguments.
__exit__ receives three arguments (exc_type, exc_val, exc_tb); they are None when no exception occurs.
Context Application Scenarios
Enhancing functionality before and after code execution (similar to decorators).
Resource management, e.g., closing files, network connections, database connections.
Permission checks performed in __enter__ before code runs.
contextlib.contextmanager
This decorator turns a generator function into a context manager, avoiding the need to implement __enter__ and __exit__ in a class.
Reflection‑Related Functions and Methods
Built‑in Reflection Functions
getattr(object, name[, default]) – returns attribute value or default.
setattr(object, name, value) – sets or creates an attribute.
hasattr(object, name) – checks if an attribute exists.
Reflection Magic Methods
__getattr__()
class Base:
n = 0
class Point(Base):
z = 6
def __init__(self, x, y):
self.x = x
self.y = y
def __getattr__(self, item):
return f"missing {item}"
p = Point(4, 5)
print(p.x) # 4
print(p.z) # 6
print(p.n) # 0
print(p.t) # missing tIf an attribute is not found via normal lookup, __getattr__ is called; otherwise an AttributeError is raised.
setattr()
class Point(Base):
def __setattr__(self, key, value):
print(f"setattr {key}={value}")
self.__dict__[key] = valueIntercepts attribute creation or modification; you must update __dict__ manually for the change to take effect.
__getattribute__
class Base:
n = 0
class Point(Base):
z = 6
def __init__(self, x, y):
self.x = x
self.y = y
def __getattribute__(self, item):
return item # simplistic example__getattribute__ is invoked for *every* attribute access; it must delegate to the superclass to avoid infinite recursion and should return the computed value or raise an exception, after which __getattr__ may be called if the attribute is still missing.
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.
