English

What is the use of __init__? When is it called? Explain with an example.

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?
Chapter 3: Classes in Python - EXERCISE [Page 62]

APPEARS IN

CBSE Computer Science with Python [English] Class 12
Chapter 3 Classes in Python
EXERCISE | Q 7. | Page 62
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×