हिंदी

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×