Plain objects versus slotted objects
The program prints comparisons, not byte counts, because sizes differ between builds (this page is a 32-bit WebAssembly build). On your own machine print sys.getsizeof values to see the real numbers.
By default every object carries its own __dict__ for attributes, which costs memory. Declaring __slots__ stores attributes in a fixed layout instead, saving memory for millions of small objects and blocking accidental new attributes, at the price of flexibility.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a slotted class Point with x and y. Show that assigning p.z = 1 raises AttributeError and print Point.__slots__.
Write a function has_dict(obj) that returns whether an object has a __dict__, and show it for a plain object and a slotted object.
Create a Cell class with __slots__ = ("value", "__weakref__"). Make a weak reference to one, delete the object and print what the reference returns.
Explain it without notes
Why does a normal Python object use more memory than a slotted one?
What do you gain and lose by adding __slots__?
Why can't you trust sys.getsizeof alone to measure memory?
What is a weak reference, and what does it have to do with slots?
Expected output
True False
['a', 'b', 'c']
AttributeError: 'Slim' object has no attribute 'd' and no __dict__ for setting new attributes
4
TypeError: vars() argument must have __dict__ attribute
1 2 3 ('a', 'b', 'c')
slots object is smaller: True
pointer size in bits: 32
True
5
None