Reading-Notes

View the Project on GitHub MohammadAl-khatib/Reading-Notes

Pythonisms

Dunder Methods

Dunder methods are predefined built-in methods that you can redefine to enrich your classes, some well known dunder methods are __str__, __repr__, and __init__.

You can see Python’s data model as a powerful API you can interface with by implementing one or more dunder methods. If you want to write more Pythonic code, knowing how and when to use dunder methods is an important step.

The following features can be unlocked with dunder methods:

  1. Initialization of new objects
  2. Object representation
  3. Enable iteration
  4. Operator overloading (comparison)
  5. Operator overloading (addition)
  6. Method invocation
  7. Context manager support (with statement)

Examples of using dunder methods are using __repr__ to return a documentation of the class, __str__ to specify what to return when an instance of the class is printed, and __init__ to create a constructor for the class, other examples with written code can be found here

Iterators

Iterators are the methods that allow you to iterate over some objects like lists and strings, primarily, iterators need two dunder methods to work: __iter__ and __next__, these functions can be called eighther as obj.__iter__ or iter(obj), in order to make iterator not loop infinitly, we need a condition to check inside next dunder method, when this condition is met, an exception is raised and looping stops [Resource].

Generators:

Needs better focus, to be continued Resource