The init method in Python is a special instance method known as the initializer. It is automatically called when a new instance of a class is created. Its primary purpose is to initialize the attributes of the new object with specific values, which can be passed as arguments when creating the object. Key points about init in Python:
- It initializes an object's attributes at the time of creation, setting up its initial state.
- It is called right after the object is created by the actual constructor method new.
- The method always takes at least one argument, self, which refers to the instance being created.
- You can define other parameters after self to receive values for initializing the object's attributes.
- It allows objects to be personalized with different data immediately upon creation.
- It is commonly used to set default or initial values for attributes in classes.
Example:
python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person1 = Person("Alice", 30)
print(person1.name) # Output: Alice
print(person1.age) # Output: 30
Here when person1
is created, init is called with "Alice" and 30 to
initialize the person's name and age attributes. Unlike some languages,
Python's init is not the constructor but an initializer; the actual object
creation is done by new , which is called before init. In summary,
init is essential for setting up objects with the necessary initial state
and values, making classes flexible and their instances meaningful from the
moment they are created. This explanation is based on Python documentation and
multiple tutorials on init , including its distinction from new ,
usage in inheritance, and common practical examples.