reading-notes

Software Development Reading Notes

View on GitHub

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:

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/)