Reading-Notes

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

Game of Greed 4

Dunder Methods

Dunder methods are built in methods that start with double under score __, we used to deal with some of them like __str__ , __repr__ and __init__, in this article we will have more dunder method examples:

  1. ` len`:

    Returns the number of occurrences of a selected property.

  2. __getitem__:

    Returns the value of a selected item by a selected property (inside defintion) and index

  3. __eq__:

    Defines what equal sign (=) does when used with class instances

  4. __lt__:

    Defines what less than sign (<) does when used with class instances

  5. __add__:

    Defines what plus sign (+) does when used with class instances

There is a large number of these dunder methods, in order to define, or override, the default way of any dunder method, it must be defined inside the class, inside the body of the method the required new behavior is defined.

Example:

def __add__(self, other):

    owner = self.owner + other.owner

    start_amount = self.balance + other.balance

    return Account(owner, start_amount)

In this example using the + sign with instances will cause it to create and return a new object with properties from the objects called before and after the plus sign.