Playtime in the Dunders
These are materials to accompany my
on improving ones python skills through having fun with the
double underscore (dunder) special python methods.
The misfit class:
- Try making a dictionary keyed by
- See what happens when you assign to keys, retrieve values
- Look at sets that contain
- Add a
CarKey to the set multiple times.
- Try changing the
CarKey hash to return either 1 or 9.
- As of CPython 3.7.0, dictionaries start with eight hash
buckets. Try adding the 1-9
CarKey to a dictionary. Then
observe the change in behavior when more keys are added.
- For the truly curious, you can see how buckets are selected
from the hash from the CPython
source code comments
(as of this writing)
The correctly adding version:
Addition at work:
>>> three = ChurchInt(3)
>>> four = ChurchInt(4)
>>> seven = three + four
>>> y7 = seven(yolo)
- Try adding other mathematical operations.
- Once you implement multiplication you can even do
“Resurrecting” version of the object:
- Try making the object and deleting all references to it.
Add an init method with a self reference:
Now the object will need to wait on the garbage collector for
destruction due to the circular reference. You can do
import gc; gc.collect() to make the garbage collector run.