Understanding __init__ in Python

The __init__ Method

The __init__ method in Python is a special method that plays a crucial role in object-oriented programming. It is automatically invoked when a new object of a class is instantiated. The primary purpose of the __init__ method is to initialize the instance variables of a class, setting up the initial state of the object. This method can also take arguments, allowing for customization of the object upon creation.

Key Characteristics of __init__:

  • Initialization: It is used to initialize the attributes of the newly created object.
  • Customization: By accepting arguments, it allows for the customization of the object during its creation.
  • Automatic Invocation: It is automatically called when an instance of a class is created.

Example Usage

Here is an example of how the __init__ method is used in a class:

class TypedList:
    def __init__(self, example_element, initial_list=[]):
        self.type = type(example_element)
        if not isinstance(initial_list, list):
            raise TypeError("Second argument of TypedList must " 
                            "be a list.")
        for element in initial_list: 
            self.__check(element)
        self.elements = initial_list[:]

In this example, the TypedList class uses the __init__ method to ensure that the initial_list is indeed a list and that all its elements are of the same type as example_element.

Another example demonstrates how __init__ can be overridden to enforce specific constraints:

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    key_error = any(not isinstance(_, str) for _ in self.keys())
    if key_error:
        raise TypeError('key is not a string')
    value_error = any(not isinstance(_, str) for _ in self.values())
    if value_error:
        raise TypeError('value is not a string')

In this snippet, the __init__ method is overridden to ensure that only strings are allowed as keys and values in a dictionary-like class.

The __init__.py File

Apart from the __init__ method, Python also uses a special file named __init__.py. This file serves two main purposes:

  1. Package Recognition: It allows Python to recognize a directory as a package.
  2. Package Initialization: It is automatically executed the first time a package or subpackage is loaded, allowing for any necessary initialization.

Example of __init__.py

Here is an example of an __init__.py file:

Listing 18.1 File mathproj/init.py

print("Hello from mathproj init")
__all__ = ['comp']
version = 1.03

In this example, the __init__.py file prints a message when the package is loaded, defines the __all__ variable to specify which modules should be accessible when the package is imported, and sets a version number for the package.

FAQ (Frequently asked questions)

When is the init method called in Python?

What checks does the init method perform in the provided code snippet?