Sub topic 3
Making Objects Behave Like Python Objects
Assume you know how to define classes, instance attributes, regular methods, for loops, and with statements. Python’s data model connects syntax and built-in functions to special methods, also called dunder methods.
Making objects iterable
An iterable is an object that can produce its members one at a time. A for loop first calls __iter__(), which should return an iterator. The iterator supplies values through __next__() and raises StopIteration when it is finished.
class Countdown:
def __init__(self, start):
self.start = start
def __iter__(self):
current = self.start
while current > 0:
yield current
current -= 1
for number in Countdown(3):
print(number) # 3, 2, 1A generator function, identified by yield, creates the iterator automatically. Each call to iter(Countdown(3)) creates a fresh sequence.
Callable objects with `__call__`
Implement __call__ when an instance represents an action that should retain state. The instance can then be used with function-call syntax.
class Counter:
def __init__(self):
self.value = 0
def __call__(self, step=1):
self.value += step
return self.value
counter = Counter()
print(counter()) # 1
print(counter(5)) # 6
print(callable(counter)) # TrueContext managers
A context manager controls setup and cleanup around a with block. __enter__ runs at the start. __exit__ runs at the end, including when the block raises an exception.
Return False from __exit__ to let exceptions propagate.
class Managed:
def __enter__(self):
print("start")
return self
def __exit__(self, exc_type, exc, traceback):
print("cleanup")
return FalseDynamic attributes and descriptors
__getattr__ runs only when normal attribute lookup fails. It is useful for computed fallback values.
A descriptor is a class attribute that controls access through __get__ and __set__. Use descriptors for reusable behavior such as validation.
class Positive:
def __set_name__(self, owner, name):
self.private_name = "_" + name
def __get__(self, obj, objtype=None):
if obj is None:
return self
return getattr(obj, self.private_name)
def __set__(self, obj, value):
if value <= 0:
raise ValueError("must be positive")
setattr(obj, self.private_name, value)
class Product:
price = Positive()
def __init__(self, price):
self.price = priceWhen to overload
Overload a special method when the operation has an unsurprising meaning for your type. Keep behavior consistent with built-in objects. Return NotImplemented for unsupported operand types so Python can try another implementation.
Avoid clever meanings, hidden side effects, and overloaded operators that merely replace a clearly named method.
Exercise
Why should an iterable usually return a new iterator from _iter_()?
Show answer
A new iterator lets separate for loops start from the beginning instead of sharing exhausted state.