What is the role of the __init__() method in Python classes?

What is the role of the __init__() method in Python classes?

a) It initializes the object’s attributes when it is created
b) It defines the string representation of the object
c) It compares two objects
d) It deletes an object from memory

Answer:

a) It initializes the object’s attributes when it is created

Explanation:

The __init__() method in Python classes is a special method called a constructor. It is automatically invoked when an object of the class is created and is used to initialize the object’s attributes with the values provided during the object’s creation.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

# Creating an object of Person class
person = Person("Alice", 30)
person.greet()  # Output: Hello, my name is Alice and I am 30 years old.

In this example, the __init__() method initializes the name and age attributes of the Person class. These attributes are then used in other methods of the class, like greet().

Understanding the __init__() method is crucial for creating objects that are properly set up with the necessary initial data, making them ready to be used immediately after creation.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top