मराठी

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

Advertisements
Advertisements

प्रश्न

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

कोड लेखन
स्पष्ट करा
Advertisements

उत्तर

__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
  या प्रश्नात किंवा उत्तरात काही त्रुटी आहे का?
पाठ 3: Classes in Python - EXERCISE [पृष्ठ ६२]

APPEARS IN

सीबीएसई Computer Science with Python [English] Class 12
पाठ 3 Classes in Python
EXERCISE | Q 7. | पृष्ठ ६२
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×