The __init__ Method in Python Classes

The __init__ method is automatically executed whenever a class is instantiated. It’s often referred to as the constructor because it initializes the object’s key properties.

Note: There are two underscores before and after the word "init," for a total of four underscores.

How It Works

This method accepts input values and assigns them to the class attributes.

The first parameter is always a reference to the object that is being created.

Typically, the word self is used for this reference.

Why use "self"? Although you can technically use any name, "self" is the convention, which helps keep the code more readable. Most Python developers stick to this convention.

It’s essentially just a placeholder word.

When you create an object, you don’t need to explicitly pass "self" as a parameter; the interpreter handles it for you.

A Practical Example

Let’s create a class:

  1. class ClassName():
  2. def __init__(self, attribute_value):
  3. self.attribute = attribute_value

This sample class has a single attribute.

It accepts a value as input and assigns it to a specific attribute of the class.

For instance, in this class, the attribute represents a person’s name.

  1. class Person():
  2. def __init__(self, name):
  3. self.name = name

The value to be assigned is provided when an instance of the class is created.

In this example, the class is called Person().

Here’s how you create an instance:

colleague = Person("Andrea")

Once the instance is created, you can access the object's attributes using the Person() class.

If you type:

colleague.name

Python will return:

'Andrea'

And that’s it.

 
 

Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

FacebookTwitterLinkedinLinkedin
knowledge base

Python Classes