Pythonisms

Dunder (Magic, Special) Methods

Object Initialization: init

Object Representation: str, repr

Iteration: len, getitem, reversed

Operator Overloading for Comparing Accounts: eq, lt

Operator Overloading for Merging Accounts: add

Callable Python Objects: call

Context Manager Support and the With Statement: enter, exit

Python Iterators

Iterators provide a sequence interface to Python objects that’s memory efficient and considered Pythonic. Behold the beauty of the for-in loop! To support iteration an object needs to implement the iterator protocol by providing the iter and next dunder methods. Class-based iterators are only one way to write iterable objects in Python. Also consider generators and generator expressions.

Python Generators

def repeater(value): while True: yield value

iterator = repeat_three_times(‘Hey there’) next(iterator) ‘Hey there’ next(iterator) ‘Hey there’ next(iterator) ‘Hey there’ next(iterator) StopIteration next(iterator) StopIteration