67.5k views
3 votes
Can somoene explain the function of-

def __init__():

In python programming language​

User Tardis
by
5.7k points

1 Answer

7 votes

Answer:

def is a keyword used to define a function, placed before a function name provided by the user to create a user-defined function

__init__ is one of the reserved methods in Python. In object oriented programming, it is known as a constructor. Python will call the __init__() method automatically when you create a new object of a class, you can use the __init__() method to initialize the object’s attributes.

Example code:

class Person:

def __init__(self, name, age):

self.name = name

self.age = age

p1 = Person("John", 36)

print(p1.name)

print(p1.age)

Summary

  • Use the __init__() method to initialize the instance attributes of an object.
  • The __init__() doesn’t create an object but is automatically called after the object is created.
User Niels Ganser
by
6.7k points