Pythonisms
Dunder (Magic, Special) Methods
- Definition:
a set of predefined methods you can use to enrich your classes. They are easy to recognize because they start and end with double underscores,
- Example: init or str
- Useful, but it’s recommended not to over use them.
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
-
Code Example 1(without and with using Python Generators):
class Repeater: def init(self, value): self.value = value
def iter(self): return self
def next(self): return self.value
def repeater(value): while True: yield value
-
Code Example 2:
def repeat_three_times(value): yield value yield value 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