Python

Write an awesome doc for Python. A very nice an practical one extracted from Python official documentation.

View on GitHub

Dunder Methods

__init__

class Animal:
    """
    Create an animal

    Attributes:
        name: The name of the animal.
        species: The species of the animal.
    """

    def __init__(self, name: str, species: str):
        self.name = name
        self.species = species

[!TIP]

In python we have in fact two method which will be called when an object is instantiated, __new__ and __init__. __new__ is called first and it’s responsible for creating the object, while __init__ is called second and it’s responsible for initializing the object.

__str__

class BankAccount:
    """
    Create a bank account

    Attributes:
        account_number: The account number.
        balance: The balance of the account.
    """

    def __init__(self, account_number: int, balance: float):
        self.account_number = account_number
        self.balance = balance

    def __str__(self):
        return f"Account Number: {self.account_number}, Balance: {self.balance}"

my_account = BankAccount(123456789, 1000.0)
print(my_account)

YouTube/Aparat