Advertisements
Advertisements
Question
What is the use of __init__? When is it called? Explain with an example.
Code Writing
Explain
Advertisements
Solution
__init__ is a special method used to initialise the instance attributes of an object. It is called automatically whenever a new object of the class is created.
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def display(self):
print(self.name, self.marks)
s1 = Student("Riya", 95) # __init__() is called automatically
s1.display()
Riya 95
Here, Student("Riya", 95) automatically invokes __init__ to initialise name and marks.
shaalaa.com
Is there an error in this question or solution?
