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:
- class ClassName():
- def __init__(self, attribute_value):
- 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.
- class Person():
- def __init__(self, name):
- 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.