Dunder Methods
doulbe underscores is the format, dunder methods are predefined methods that let you emulate the behavior of built-in types. through dunder we can do the following:
- Initialization of new objects: e.g.
__init__
- Object representation: e.g.
__str__
- Enable iteration: e.g.
__len__
- Operator overloading (comparison): e.g.
dir()
builtin with a bunch of dunders e.g.__eq__
- Operator overloading (addition): e.g.
__add__
- Method invocation: e.g.
__call__
- Context manager support (with statement): e.g.
__enter__
Dunder methods often come with the self
as their default params
Python Iterators
“Objects that support the iter and next dunder methods automatically work with for-in loops.”
for-in loops format:
repeater = Repeater('Hello') for item in repeater: print(item)
Python Generators
this allows you to write concise for-in loops. in generators, functions do not use return statements, instead, they use
yield
to pass data back to the caller.
Through generators, we can short this seven lines of code:
class Repeater:
def __init__(self, value):
self.value = value
def __iter__(self):
return self
def __next__(self):
return self.value
to 2 lines of beauty code: (generators format)
def repeater(value):
while True:
yield value
(code samples are from the articles in https://dbader.org/)