__init__ method
The __init__
Method in Python
In Python, the __init__
method is a special method (also known as a constructor) that is automatically called when an instance of a class is created. Its primary purpose is to initialize the attributes of the object.
Basic Syntax
class MyClass:
def __init__(self, parameter1, parameter2, ...):
# Initialize instance variables here
self.attribute1 = parameter1
self.attribute2 = parameter2
# ...
# Creating an instance of the class
obj = MyClass(arg1, arg2, ...)
Key points about the __init__
method:
- Name and Double Underscores: The method name is
__init__
with a double underscore before and after "init." self
Parameter: The first parameter of the__init__
method isself
. This parameter refers to the instance of the class being created and is passed automatically.- Attributes Initialization: Inside the
__init__
method, you can initialize instance variables (attributes) using theself
keyword. - Initialization Code: The
__init__
method is often used to perform any setup or initialization required for the object.
Example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f"Hi, I'm {self.name}, and I'm {self.age} years old.")
# Creating instances of the class
person1 = Person(name="Alice", age=25)
person2 = Person(name="Bob", age=30)
# Accessing attributes and calling methods
person1.introduce() # Output: Hi, I'm Alice, and I'm 25 years old.
person2.introduce() # Output: Hi, I'm Bob, and I'm 30 years old.
In this example, the __init__
method initializes the name
and age
attributes for each instance of the Person
class. When creating instances (person1
and person2
), values are passed for these attributes.
The __init__
method is a fundamental part of Python classes and is commonly used to set up the initial state of objects. It provides a way to ensure that necessary attributes are properly initialized when creating instances of a class.