Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The `__init__` function in Python is a special method called a constructor. It is automatically invoked when an instance of a class is created. Its primary purpose is to initialize the object’s attributes.
Here’s how it works:
Definition: It starts with `def __init__(self, …)` and includes the `self` parameter, which refers to the instance being created.
Initialization: You can pass additional parameters to `__init__` to set initial values for the object’s attributes.
Example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person(“Alice”, 30)
print(p1.name) # Output: Alice
print(p1.age) # Output: 30
In this example, the `__init__` method initializes `name` and `age` attributes for the `Person` class. When creating an instance (`p1`), `”Alice”` and `30` are passed as arguments, setting the initial state of the object. The `__init__` method ensures that these attributes are properly set when the object is created.