Python Quiz Question
Python Quiz Question
What is the primary purpose of the __init__ method in Python classes?
a) To define a class variable
b) To create an instance of the class
c) To initialize the instance variables of a class
d) To delete an instance of the class
Correct Answer
c) To initialize the instance variables of a class
Explanation
The __init__ method in Python is a special method automatically called when a new class instance is created. Its primary purpose is to initialize the class’s instance variables. This method allows you to set an object’s initial state by assigning values to the instance variables. It is commonly used to pass values to the object during creation, ensuring it is properly initialized with the required attributes.
Code Listing
# Python Quiz Question
# Create an instance of the Person class
# Python Tutorials - www.TestingDocs.com
class Person:
def __init__(self, name, age):
self.name = name # Initialize 'name'
self.age = age # Initialize 'age'
def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")
# Create an instance of the Person class
person1 = Person("John", 30)
# Display the initialized values
person1.display_info()
Class Definition: The Person class is defined with an __init__ method.
__init__ Method: This method takes self, name, and age as parameters. It initializes the instance variables: name and age.
Creating an Instance: When person1 = Person(“John”, 30) is executed, the __init__ method is called with “John” and 30 as arguments, initializing the name and age of person1.
Displaying Information: The display_info method prints the values of the name and age instance variables.
Running this code will output:
Name: John, Age: 30
This demonstrates how the __init__ method is used to initialize instance variables of a class.