Magic Methods & the Python Data Model
Published by Brayan K
Master Python's powerful magic methods (dunder methods) and understand how the Python data model works under the hood. Learn to create custom classes that behave like built-in types, implement operator overloading, and build professional-grade objects.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Python calls these methods, and looks for them on the class
This lesson is about what Python's built-in functions and statements ask an object for: len(), print(), if, for, in, calling it, and ==. Operators such as + and < have a lesson of their own, Operator Overloading & Custom Behaviours.
In Object-Oriented Programming, print() used a Point's __str__, and in Context Managers & the with Statement in Depth, with called __enter__ and __exit__. Methods named like these, with two underscores on each side, are called special methods, magic methods or dunder methods (for "double underscore"). You don't call them yourself: a built-in function or a statement calls them for you. len(b) asks b's class for __len__:
class Basket:
def __init__(self, items):
self.items = list(items)
def __len__(self):
print("__len__ called")
return len(self.items)
b = Basket(["tea", "jam"])
print(len(b))
print(Basket.__len__(b))
# ✅ Expected output:
# __len__ called
# 2
# __len__ called
# 2Python looks for the method on the class, not on the object. Giving one object a __len__ of its own changes nothing for len():
class Basket:
def __init__(self, items):
self.items = list(items)
def __len__(self):
return len(self.items)
b = Basket(["tea", "jam"])
b.__len__ = lambda: 99
print(b.__len__())
print(len(b))
# ✅ Expected output:
# 99
# 2b.__len__() calls the function stored on the object, but len(b) goes straight to Basket.__len__. And if the class has no __len__ at all, one stored on the object doesn't help: len() stops with TypeError: object of type 'Basket' has no len().
So call the built-in function, not the method. len() also checks the answer, which calling __len__ yourself doesn't:
class Countdown:
def __init__(self, start):
self.start = start
def __len__(self):
return self.start
print(len(Countdown(3)))
print(Countdown(-1).__len__())
print(len(Countdown(-1)))
# ✅ Expected output:
# 3
# -1
# ✅ Expected error:
# ValueError: __len__() should return >= 0A length that isn't a whole number is refused too: a __len__ returning 2.5 makes len() stop with TypeError: 'float' object cannot be interpreted as an integer.
print(), repr() and f-strings each ask their own method
Object-Oriented Programming showed that print(), str() and f-strings use __str__, while lists and !r use __repr__, which is also what print() falls back on. Here is each place a Price shows up:
class Price:
def __init__(self, pence):
self.pence = pence
def __repr__(self):
return f"Price({self.pence})"
def __str__(self):
return f"£{self.pence / 100:.2f}"
p = Price(250)
print(p)
print(str(p), repr(p))
print([p, Price(99)])
print({"tea": p})
print(f"{p} and {p!r}")
print(f"{p=}")
# ✅ Expected output:
# £2.50
# £2.50 Price(250)
# [Price(250), Price(99)]
# {'tea': Price(250)}
# £2.50 and Price(250)
# p=Price(250)A list and a dictionary show their items' reprs, and f"{p=}", the form from f-strings & String Formatting that shows a name with its value, uses the repr as well. With only __str__, the list would show each price as <__main__.Price object at 0x…>, the default repr, with a memory address that changes from run to run.
A format spec, the part after the colon in {p:>8}, goes to a third method, __format__. The one every class starts with accepts no spec at all, the same error f-strings & String Formatting showed for None:
class Price:
def __init__(self, pence):
self.pence = pence
def __str__(self):
return f"£{self.pence / 100:.2f}"
p = Price(250)
print(f"{p}")
print(f"{p:>8}")
# ✅ Expected output:
# £2.50
# ✅ Expected error:
# TypeError: unsupported format string passed to Price.__format____format__ receives the spec as a string. format(text, spec) applies a spec the way an f-string's colon does, so handing the spec on to the text gets padding and alignment for nothing, and the method can add specs of its own:
class Price:
def __init__(self, pence):
self.pence = pence
def __str__(self):
return f"£{self.pence / 100:.2f}"
def __format__(self, spec):
if spec == "p":
return f"{self.pence}p"
return format(str(self), spec)
p = Price(250)
print(f"[{p}]")
print(f"[{p:p}]")
print(f"[{p:>8}]")
# ✅ Expected output:
# [£2.50]
# [250p]
# [ £2.50]When is an object true? __bool__, then __len__
if, while, not and bool() all ask an object whether it's true. An object whose class has neither __bool__ nor __len__ is always true. With __len__, it's false when the length is 0, like an empty list:
class Bag:
def __init__(self, items):
self.items = list(items)
class Basket:
def __init__(self, items):
self.items = list(items)
def __len__(self):
return len(self.items)
print(bool(Bag([])), bool(Basket([])), bool(Basket(["tea"])))
basket = Basket([])
if not basket:
print("nothing to pay for")
# ✅ Expected output:
# True False True
# nothing to pay forWhen the class has a __bool__, it's asked first, and it must return True or False. Returning the length isn't enough:
class Basket:
def __init__(self, items):
self.items = list(items)
def __bool__(self):
return len(self.items)
if Basket(["tea"]):
print("ready to pay")
# ✅ Expected error:
# TypeError: __bool__ should return bool, returned intreturn len(self.items) > 0 would work. Which built-in values count as false is in Booleans & Truthiness.
Square brackets, for loops and in
shelf[0] calls __getitem__ with whatever is inside the brackets: a number, a negative number, a slice or any key at all. A slice arrives as a slice object, slice(0, 2, None), which a list accepts as it is:
class Shelf:
def __init__(self, books):
self.books = list(books)
def __getitem__(self, key):
print("asked for", repr(key))
return self.books[key]
shelf = Shelf(["Dune", "Emma", "Ulysses"])
print(shelf[0])
print(shelf[-1])
print(shelf[0:2])
print(shelf["Emma"])
# ✅ Expected output:
# asked for 0
# Dune
# asked for -1
# Ulysses
# asked for slice(0, 2, None)
# ['Dune', 'Emma']
# asked for 'Emma'
# ✅ Expected error:
# TypeError: list indices must be integers or slices, not strThe string reached __getitem__ too: it was the list inside that refused it.
__getitem__ alone is enough for a for loop. When the class has no __iter__, the loop asks for item 0, then 1, then 2, and stops at the first IndexError:
class Shelf:
def __init__(self, books):
self.books = list(books)
def __getitem__(self, i):
print("asked for", i)
return self.books[i]
for book in Shelf(["Dune", "Emma"]):
print(book)
# ✅ Expected output:
# asked for 0
# Dune
# asked for 1
# Emma
# asked for 2The same way, in, list(), sorted() and unpacking such as first, second = shelf all work. len() doesn't: it needs __len__.
That's a trap for a class that looks things up by name. Its __getitem__ raises KeyError, not IndexError, so a loop over it stops at its first question:
class Menu:
def __init__(self, prices):
self.prices = dict(prices)
def __getitem__(self, name):
return self.prices[name]
menu = Menu({"tea": 2.5, "cake": 3.0})
print(menu["tea"])
for item in menu:
print(item)
# ✅ Expected output:
# 2.5
# ✅ Expected error:
# KeyError: 0Give such a class an __iter__. Written as a generator, as in Generators & Iterators Mastery, it's a for loop with yield, and every loop over the object gets a fresh one. in asks __contains__ first, when the class has it, so it can decide what counts as a match:
class Shelf:
def __init__(self, books):
self.books = list(books)
def __iter__(self):
for book in self.books:
yield book
def __contains__(self, title):
return title.lower() in [book.lower() for book in self.books]
shelf = Shelf(["Dune", "Emma"])
print(list(shelf), list(shelf))
print("emma" in shelf, "emma" in list(shelf))
# ✅ Expected output:
# ['Dune', 'Emma'] ['Dune', 'Emma']
# True FalseAn object that keeps its own place between calls of next() is an iterator, which Iterators: __iter__ & __next__ teaches. With neither __iter__ nor __getitem__, a loop stops with TypeError: 'Basket' object is not iterable. in on such an object says TypeError: argument of type 'Basket' is not iterable up to Python 3.13, and … is not a container or iterable on 3.14.
Objects you can call: __call__
Higher-Order Functions & Function Factories said in its FAQ that callable() is True for functions, methods and classes. An object whose class has __call__ can be called too, with instance attributes holding data between calls. Functions can retain state through closures or their own attributes as well; a callable instance makes that state part of an explicit object:
class Discount:
def __init__(self, percent):
self.percent = percent
self.used = 0
def __call__(self, price):
self.used += 1
return round(price * (100 - self.percent) / 100, 2)
ten_off = Discount(10)
print(ten_off(20), ten_off(4.5))
print(ten_off.used)
print(callable(ten_off), callable(Discount), callable("ten"))
print(list(map(ten_off, [10, 30])))
# ✅ Expected output:
# 18.0 4.05
# 2
# True True False
# [9.0, 27.0]Without __call__, the brackets are an error:
class Discount:
def __init__(self, percent):
self.percent = percent
ten_off = Discount(10)
print(ten_off(20))
# ✅ Expected error:
# TypeError: 'Discount' object is not callable== with something that isn't a Point
Object-Oriented Programming gave Point an __eq__ that compares x and y. It works between two points, but == can meet anything, and in compares too:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
print(Point(1, 2) == Point(1, 2))
print(Point(1, 2) == (1, 2))
# ✅ Expected output:
# True
# ✅ Expected error:
# AttributeError: 'tuple' object has no attribute 'x'The fix is to answer only for your own class and return NotImplemented for anything else. NotImplemented is a value built into Python that means "I can't compare with that". Python then asks the other object, and if it can't answer either, == falls back on whether the two are the same object, which here means False. != uses __eq__ too and turns its answer round:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
if not isinstance(other, Point):
return NotImplemented
return (self.x, self.y) == (other.x, other.y)
print(Point(1, 2) == Point(1, 2))
print(Point(1, 2) == (1, 2))
print(Point(1, 2) != (1, 2))
print(Point(1, 2) in [None, (1, 2), Point(1, 2)])
# ✅ Expected output:
# True
# False
# True
# TrueYou can watch Python ask:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
print("Point.__eq__ asked about a", type(other).__name__)
if not isinstance(other, Point):
return NotImplemented
return (self.x, self.y) == (other.x, other.y)
p = Point(1, 2)
print(p == "Point(1, 2)")
print(p == p)
# ✅ Expected output:
# Point.__eq__ asked about a str
# False
# Point.__eq__ asked about a Point
# TrueWhy not simply return False? That answers the comparison instead of letting Python try the other type's comparison when applicable. NotImplemented supports cooperative comparison; it cannot guarantee symmetry if the other type implements inconsistent behavior. A subclass's comparison may also get priority. The __eq__ that @dataclass writes in Data Classes & Advanced Class Patterns does the same.
Equal objects need equal hashes
Dictionaries said a key needs a hash, a number worked out from it that tells the dictionary where to look. A plain user-defined class inherits identity-based equality and hashing from object. If it defines __eq__ without defining __hash__, Python sets __hash__ to None, since a hash from identity would no longer agree with ==. That's why Object-Oriented Programming's Point couldn't go in a set:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
if not isinstance(other, Point):
return NotImplemented
return (self.x, self.y) == (other.x, other.y)
print(Point.__hash__)
print(hash(Point(1, 2)))
# ✅ Expected output:
# None
# ✅ Expected error:
# TypeError: unhashable type: 'Point'In a set or as a dictionary key, the error is the same up to Python 3.13; 3.14 words it TypeError: cannot use 'Point' as a set element (unhashable type: 'Point'), or … as a dict key …. To allow it, write __hash__ from the same fields __eq__ compares. A tuple of them is the usual way, since a tuple can be hashed when its items can:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
if not isinstance(other, Point):
return NotImplemented
return (self.x, self.y) == (other.x, other.y)
def __hash__(self):
return hash((self.x, self.y))
visited = {Point(1, 2), Point(1, 2), Point(3, 4)}
print(len(visited))
print(Point(1, 2) in visited)
labels = {Point(0, 0): "home"}
print(labels[Point(0, 0)])
# ✅ Expected output:
# 2
# True
# homeThe one rule is that objects that are equal must have the same hash. A set or a dictionary finds an object by its hash first, and only then compares with ==. So an object mustn't change those fields while it's in a set or used as a key. Changing the hash makes lookups unreliable: the entry remains stored according to its old hash. In this example neither a lookup by the old coordinates nor one by the new coordinates finds it:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
if not isinstance(other, Point):
return NotImplemented
return (self.x, self.y) == (other.x, other.y)
def __hash__(self):
return hash((self.x, self.y))
p = Point(1, 2)
seen = {p}
p.x = 5
print(p in seen)
print(Point(1, 2) in seen, Point(5, 2) in seen)
print(len(seen))
# ✅ Expected output:
# False
# False False
# 1That's why a dataclass made with frozen=True gets a hash and a plain one doesn't, and why a list can't be a dictionary key.
__new__ makes the object, __init__ fills it in
Object-Oriented Programming's FAQ said __init__ isn't quite the constructor. Python first calls __new__ on the class to make the object, then __init__ on the new object to set it up:
class Ticket:
def __new__(cls, number):
print("__new__ makes a", cls.__name__)
return super().__new__(cls)
def __init__(self, number):
print("__init__ stores", number)
self.number = number
t = Ticket(7)
print(t.number)
# ✅ Expected output:
# __new__ makes a Ticket
# __init__ stores 7
# 7super().__new__(cls) is object's own __new__, which makes an empty object of class cls. You rarely need a __new__ of your own, except in one case: a class built on a type whose objects can't change, such as str, int or tuple. By the time __init__ runs, the text is already made, so only __new__ can decide it:
class Upper(str):
def __init__(self, text):
text = text.upper()
class Shout(str):
def __new__(cls, text):
return super().__new__(cls, text.upper())
print(Upper("tea"), Shout("tea"))
print(Shout("tea") + "pot", isinstance(Shout("tea"), str))
# ✅ Expected output:
# tea TEA
# TEApot TrueUpper's __init__ ran, but assigning to text only changed a local variable. A __new__ that forgets return hands back None, and Python doesn't call __init__ on something that isn't an object of the class:
class Ticket:
def __new__(cls, number):
super().__new__(cls)
def __init__(self, number):
self.number = number
t = Ticket(7)
print(t)
print(t.number)
# ✅ Expected output:
# None
# ✅ Expected error:
# AttributeError: 'NoneType' object has no attribute 'number'A __new__ that hands back the same object every time is a common way to write a singleton, a class with only one object, and it has a catch: __init__ still runs on every call. Design Patterns in Python (Singleton, Factory, Strategy) shows it, and simpler ways.
Where the other special methods are taught
Python has many more special methods. Each of these belongs with the feature that asks for it, so its own lesson teaches it:
| Methods | Asked for by | Lesson |
|---|---|---|
| __add__, __lt__, __iadd__, __neg__, __index__ | operators, ordering, int() | Operator Overloading & Custom Behaviours |
| __enter__, __exit__ | with | Context Managers & the with Statement in Depth |
| __aenter__, __aexit__ | async with | Advanced Async & Await Patterns |
| __iter__ returning self, __next__ | next(), iterators | Iterators: __iter__ & __next__ |
| __del__ | freeing an object | Memory Management & Garbage Collection Internals |
| __getattr__, __setattr__, __init_subclass__, metaclasses | attribute access, making classes | Metaprogramming & Introspection with inspect |
| __get__, __set__, __set_name__ | attributes looked up through the class | Properties & Descriptors |
| __slots__ | a class setting | __slots__ & Memory Optimization |
| __getstate__, __setstate__, __reduce__ | pickle | Serialization with pickle |
| __class_getitem__ | Box[int] in type hints | Advanced Type Hints (Generics, Protocol, TypedDict) |
Practice: seats as dictionary keys
A theatre books seats in a dictionary, so Seat must work as a key: __eq__ should give way on anything that isn't a seat, and the method sets and dictionaries ask for needs its name. The comment next to each blank says what goes in it, if you'd rather check than guess.
class Seat:
def __init__(self, row, number):
self.row = row
self.number = number
def __repr__(self):
return f"Seat({self.row!r}, {self.number})"
def __eq__(self, other):
if not isinstance(other, Seat):
return ___ # 👉 replace ___ with NotImplemented
return (self.row, self.number) == (other.row, other.number)
def ___(self): # 👉 replace ___ with __hash__
return hash((self.row, self.number))
booked = {Seat("A", 1): "Ada", Seat("B", 4): "Ben"}
print(booked[Seat("B", 4)])
print(Seat("A", 1) in booked, Seat("A", 2) in booked)
print(Seat("A", 1) == ("A", 1))
print(len({Seat("C", 9), Seat("C", 9)}))
# ✅ Expected output:
# Ben
# True False
# False
# 1Run it before filling the blanks, and the dictionary stops at its first key: with __eq__ and no __hash__, a Seat can't be hashed. Python 3.10 to 3.13 say TypeError: unhashable type: 'Seat', and 3.14 says TypeError: cannot use 'Seat' as a dict key (unhashable type: 'Seat').
On your own: a bookcase that acts like a collection
Write a class Bookcase with a name and a list of titles. Printing one shows Fiction: 3 books; repr() shows Bookcase('New', []); len() counts the titles; case[-1] is the last title; "dune" in case ignores upper and lower case; a bookcase with no titles is false, with no __bool__; and two bookcases are equal when their names and titles are, while comparing one with another type returns NotImplemented so Python can try that type's comparison. Comparing it with the ordinary string in the test is False. The lines under the comment test all of it.
# your code here
fiction = Bookcase("Fiction", ["Dune", "Emma", "Ulysses"])
empty = Bookcase("New", [])
print(fiction)
print(repr(empty))
print(len(fiction), fiction[-1])
print("dune" in fiction, "Odyssey" in fiction)
for case in [fiction, empty]:
if case:
print(case.name, "has books")
else:
print(case.name, "is empty")
print(fiction == Bookcase("Fiction", ["Dune", "Emma", "Ulysses"]), fiction == "Fiction")class Bookcase:
def __init__(self, name, titles):
self.name = name
self.titles = list(titles)
def __repr__(self):
return f"Bookcase({self.name!r}, {self.titles!r})"
def __str__(self):
return f"{self.name}: {len(self)} books"
def __len__(self):
return len(self.titles)
def __getitem__(self, i):
return self.titles[i]
def __contains__(self, title):
return title.lower() in [t.lower() for t in self.titles]
def __eq__(self, other):
if not isinstance(other, Bookcase):
return NotImplemented
return (self.name, self.titles) == (other.name, other.titles)
fiction = Bookcase("Fiction", ["Dune", "Emma", "Ulysses"])
empty = Bookcase("New", [])
print(fiction)
print(repr(empty))
print(len(fiction), fiction[-1])
print("dune" in fiction, "Odyssey" in fiction)
for case in [fiction, empty]:
if case:
print(case.name, "has books")
else:
print(case.name, "is empty")
print(fiction == Bookcase("Fiction", ["Dune", "Emma", "Ulysses"]), fiction == "Fiction")
# ✅ Expected output:
# Fiction: 3 books
# Bookcase('New', [])
# 3 Ulysses
# True False
# Fiction has books
# New is empty
# True FalseIt has no __hash__, on purpose: its list of titles can change, so a Bookcase shouldn't be a key, and {fiction} stops with the unhashable error.
Practice quiz
Basket's __len__ returns len(self.items). The program makes b = Basket(["tea", "jam", "milk"]), sets b.__len__ = lambda: 0, then runs print(len(b), bool(b)). What does it print?
- 0 False
- 3 True
- 3 False
- It stops with TypeError: object of type 'Basket' has no len()
Answer: 3 True. len() and bool() look for __len__ on the class, Basket, so the lambda stored on the object is never asked. The basket holds three items, so it's 3 and true.
Basket has a __len__ that returns len(self.items), and no __bool__. What does print(bool(Basket([])), bool(Basket([0]))) print?
- True True
- False False
- It stops with TypeError: __bool__ should return bool, returned int
- False True
Answer: False True. Without __bool__, an object is false when its __len__ is 0. Basket([0]) holds one item, so it's true, whatever that item is.
Basket's __bool__ returns len(self.items). What does this print? if Basket([]): print("full") else: print("empty")
- It stops with TypeError: __bool__ should return bool, returned int
- empty
- full
- It stops with ValueError: __bool__ returned 0
Answer: It stops with TypeError: __bool__ should return bool, returned int. __bool__ must return True or False. Returning the length, even 0, is refused before the if can decide.
Shelf has only a __getitem__ that prints "asked" and returns self.books[i]. How many times does a for loop over Shelf(["Dune", "Emma", "Ulysses"]) print "asked"?
- 3 times
- It stops with TypeError: 'Shelf' object is not iterable
- 4 times
- It never stops
Answer: 4 times. The loop asks for items 0, 1 and 2, then asks for item 3, which raises IndexError, and that ends the loop. That's four questions.
Menu's __getitem__(self, name) returns self.prices[name], from a dictionary {"tea": 2.5, "cake": 3.0}. What does for item in Menu(...): print(item) do?
- It prints tea and cake
- It prints 2.5 and 3.0
- It stops with KeyError: 0
- It stops with TypeError: 'Menu' object is not iterable
Answer: It stops with KeyError: 0. With no __iter__, the loop asks for item 0, 1, 2… The dictionary has no key 0, and a KeyError doesn't end a loop the way an IndexError does.
Point's __eq__ is return self.x == other.x and self.y == other.y. What does print(Point(1, 2) in [None, Point(1, 2)]) do?
- It stops with AttributeError: 'NoneType' object has no attribute 'x'
- True
- False
- It stops with TypeError
Answer: It stops with AttributeError: 'NoneType' object has no attribute 'x'. in compares the point with each item in turn, None first, and that __eq__ reads other.x without checking what other is.
Point's __eq__ returns NotImplemented for anything that isn't a Point, and Point has no __hash__. What does print(Point(1, 2) == Point(1, 2)) and then print(hash(Point(1, 2))) do?
- True, then a number
- True, then it stops with TypeError: unhashable type: 'Point'
- True, then the same number as hash((1, 2))
- It stops with AttributeError before printing anything
Answer: True, then it stops with TypeError: unhashable type: 'Point'. Writing __eq__ sets the class's __hash__ to None, so the comparison works and hash() is refused.
Point has __eq__ and a __hash__ made from (self.x, self.y). After p = Point(1, 2) and seen = {p}, the program runs p.x = 5 and print(p in seen). What does it print?
- True
- It stops with KeyError
- It stops with TypeError
- False
Answer: False. The set filed p under the hash of (1, 2). Its hash is now the hash of (5, 2), so the set looks in the wrong place and doesn't find it.
Continue this course
- Previous: Data Classes & Advanced Class Patterns
- Next: Operator Overloading & Custom Behaviours — Make your objects work with +, -, *, and comparison operators
- Quick reference: Python cheat sheet › Classes
Frequently asked questions
Do I need to write __ne__ as well?
No. != calls __eq__ and turns its answer round, unless __eq__ returned NotImplemented. With the Point from this lesson, Point(1, 2) != Point(1, 2) is False, != Point(3, 4) is True, and != "text" is True. Writing __ne__ as return not self.__eq__(other) is a bug: for "text" it gives False, with a DeprecationWarning, on Python 3.10 to 3.13, and on 3.14 it stops with TypeError: NotImplemented should not be used in a boolean context.
Why is x in [x] True when x == x is False?
in checks whether an item is the very same object before it compares with ==. float("nan"), the float that stands for "not a number", isn't equal to anything, itself included, so nan == nan is False, but nan in [nan] is True.
Can __getattr__ supply __len__?
No. Python looks a special method up on the class and skips __getattr__. An object whose __getattr__ answers every name returns 3 for a.__len__(), but len(a) stops with TypeError: object of type 'Anything' has no len(). Metaprogramming & Introspection with inspect covers __getattr__.
Why does reversed() work on my class?
reversed() can work from __len__ and __getitem__ together: it asks for the last index first and counts down. For a Shelf with both, list(reversed(shelf)) gave ['Ulysses', 'Emma', 'Dune'].
How do I stop a class from being looped over?
Set the method to None in the class body. With __iter__ = None, Basket()[0] still works, but a for loop stops with TypeError: 'Basket' object is not iterable, even though __getitem__ alone would have been enough.
What type hint should __eq__ take?
other: object, since == can meet anything. With other: "Point", mypy 1.19.1 reports that argument 1 of "__eq__" is incompatible with supertype "builtins.object", and its notes suggest the isinstance() check with return NotImplemented that this lesson uses, which passes. Type Hints & Static Typing with mypy shows how to run mypy.
How do I decide what copy.copy() makes?
Write __copy__, and copy.copy() calls it. A Basket whose __copy__ returns Basket(self.items) gives the copy a list of its own, so appending to the copy's list leaves the original alone: ['tea'] and ['tea', 'jam']. copy.deepcopy() is in Lists and Collections.
Related lessons
- Object-Oriented Programming
- Context Managers & the with Statement in Depth
- f-strings & String Formatting
- Booleans & Truthiness
- Generators & Iterators Mastery
- Iterators: __iter__ & __next__
- Higher-Order Functions & Function Factories
- Dictionaries
- Design Patterns in Python (Singleton, Factory, Strategy)
- Advanced Async & Await Patterns
- Memory Management & Garbage Collection Internals
- Metaprogramming & Introspection with inspect