Sub topic 2
Truth, Operators, and Container Protocols
Assume you know how to define classes, instance attributes, methods, lists, tuples, and for loops. Python’s data model connects ordinary syntax to special methods, often called dunder methods because their names begin and end with double underscores.
Truth value and numeric conversions
Python asks an object for its truth value in conditions and bool():
__bool__()should returnTrueorFalse.- If
__bool__()is absent, Python uses__len__(). Zero means false. __int__()supportsint(value).__float__()supportsfloat(value).__index__()supports exact integer contexts such as slicing andbin().
class Score:
def __init__(self, value):
self.value = value
def __bool__(self):
return self.value > 0
def __int__(self):
return self.value
def __index__(self):
return self.value
score = Score(3)
print(bool(score)) # True
print(int(score)) # 3
print("python"[score:]) # on"[?] The slice example above is intentionally problematic: "python"[score:] starts at index 3, so it prints hon. A conversion method should represent the object’s meaning, not merely make unrelated syntax work.
Arithmetic and reflected operators
Operators call methods such as __add__() and __mul__(). Return a new object when the class is immutable. Return NotImplemented for an unsupported type. This lets Python try the other operand’s reflected method, such as __radd__().
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f"Vector({self.x}, {self.y})"
def __add__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return Vector(self.x + other.x, self.y + other.y)
def __mul__(self, scalar):
if not isinstance(scalar, (int, float)):
return NotImplemented
return Vector(self.x * scalar, self.y * scalar)
__rmul__ = __mul__
def __neg__(self):
return Vector(-self.x, -self.y)
def __abs__(self):
return (self.x**2 + self.y**2) ** 0.5
def __iadd__(self, other):
self.x += other.x
self.y += other.y
return self-vector calls __neg__(), and abs(vector) calls __abs__(). v += w calls __iadd__() when available. Mutating in place is efficient, but it can surprise callers who expect a new value.
Container-like classes
__len__() and __getitem__() provide length, indexing, slicing, iteration, and often reversed(). Define __contains__() when membership needs custom behavior.
class Playlist:
def __init__(self, songs):
self._songs = list(songs)
def __len__(self):
return len(self._songs)
def __getitem__(self, index):
return self._songs[index]
def __contains__(self, song):
return song in self._songsExercise
Which method should a class implement so 3 * value can work when value * 3 already works?
Show answer
Implement __rmul__(), often by assigning __rmul__ = __mul__ when the operation is symmetric.