What is __init__ method?
In Python, the `__init__` method is a special method, often referred to as the 'constructor' or 'initializer' for a class. It is automatically called when a new instance (object) of a class is created, allowing you to set up the initial state of the object.
Purpose of __init__
The primary purpose of __init__ is to initialize the attributes of an object with specific values. These values can be hardcoded defaults, or they can be passed as arguments when the object is created.
It ensures that every new object starts with a defined set of properties, making the object ready to be used as soon as it's instantiated.
Syntax
class MyClass:
def __init__(self, arg1, arg2):
self.attribute1 = arg1
self.attribute2 = arg2
The self parameter is a convention and refers to the instance of the class itself. It must be the first parameter of the __init__ method (and any instance method). The subsequent parameters (arg1, arg2) are the values that you want to pass when creating an object.
Example
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
return f"{self.name} says Woof!"
# Creating instances of the Dog class
my_dog = Dog("Buddy", "Golden Retriever")
other_dog = Dog("Lucy", "Labrador")
print(my_dog.name) # Output: Buddy
print(other_dog.breed) # Output: Labrador
print(my_dog.bark()) # Output: Buddy says Woof!
In this example, when my_dog = Dog("Buddy", "Golden Retriever") is executed, the __init__ method of the Dog class is called automatically. self refers to the my_dog object, name gets "Buddy", and breed gets "Golden Retriever". These values are then assigned to self.name and self.breed, respectively.
Key Characteristics
- Automatic Call: It's called automatically when an object is created.
- Initialization: Its primary role is to initialize the object's attributes.
selfParameter: The first parameter must always beself, referring to the current instance.- No Return Value:
__init__does not explicitly return a value. The object itself is returned implicitly after initialization. - Optional: A class can exist without an
__init__method. In such cases, Python provides a default__init__that does nothing.
Understanding __init__ is fundamental to object-oriented programming in Python, as it defines how new objects are configured upon creation, ensuring they are always in a valid and ready-to-use state.