Reading-Notes


Project maintained by eslamakram Hosted on GitHub Pages — Theme by mattgraham

Enriching Your Python Classes With Dunder (Magic, Special) Methods

Dunder methods, a short form of “double under.” or “special methods” in Python are also sometimes called “magic methods.” But using this terminology can make them seem more complicated than they really are—at the end of the day there’s nothing “magical” about them.

The Python class with various dunder methods to unlock the following language features:

  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)

Object Initialization: __init__ To construct account objects from the Account class I need a constructor which in Python

Object Representation: __str__, __repr__ There are two ways to do this using dunder methods:

  1. repr: The “official” string representation of an object. This is how you would make an object of the class. The goal of repr is to be unambiguous.

  2. str: The “informal” or nicely printable string representation of an object. This is for the enduser.

Iteration: __len__, __getitem__, __reversed__ Operator Overloading for Comparing Accounts: __eq__, __lt__ Operator Overloading for Merging Accounts: __add__ adding two integers or two strings with the + (plus) operator

Callable Python Objects: __call__ an object callable like a regular function by adding the call dunder method

Context Manager Support and the With Statement: __enter__, __exit__