reading notes for code fellows
Dunder methods are something we’ve been using a bit so far with things like __iter__, and it should be very helpful to add some of the other possibilities to our repertiore.
Duner methods are a set of predefined methods you can use to enrich you classes by emulating the behavior of built in types. Some helpful ones are:
__init__ - initializes objects__str__ or __repr__ - represents objects__len__, __getitem__, or __reversed__ - iteration__eq__ or __lt__ - object comparison__add__ - addition/merging__call__ - makes the object callable__enter__ or __exit__ - context managementIf an object supports __iter__ and __next__ it will automatically work with for loops. A for loop is really a while loop behind the scenes that runs until it can no longer move to the next property of whatever it is iterating through. If you run all the way through an iterator, then it will raise a StopIteration exception. When you want to use these in a class, you will need both methods, one to call on itself, and the other to act as a next that can move between values and know when to stop.
A generator looks like a normal function, but is actually an object that can do something for as long as necessary. Within a generator, you can use yield to pass back control to the caller, but differently from return in a function, yield is only temporary, and retains its local state. You can use them to either iterate at a one by one rate, or leave them to run on their own depending on how you decide to call them, and they’re completely configurable, as you have to write it yourself.
It will be nice to be able to add iterators to data structures we have so they can be iterated through rather than needing to write up a function for it every time. I can see a lot of uses for generators and I’ll be interested to see how we plan to go about working with them.