WHAT IS PYTHON CONSTRUCTOR


Python Constructor-

A constructor is a special type of method or function that is used to initialize the instance members of the class.

Constructor definition is automatically executed when we create the object of the class. Constructors also verify that there are enough resources for the object to perform any start-up task.

The _init_() method simulates the constructor of the class in Python. This method is called when the class is instantiated. It accepts the self-keyword as a first argument which allows accessing the attributes or method of the class.

We can pass any number of arguments at the time of creating the class object, depending upon the _init_() definition. It is mostly used to initialize the class attributes. Every class must have a constructor, even if it simply relies on the default constructor.

Python Code

class Person:
  def __init__(self, Fname, Lname):
    self.Fname = Fname
    self.Lname = Lname

p1 = Person("John", "Doe")

print(p1.Fname)
print(p1.Lname)

output

John
Doe

Leave a Reply

Your email address will not be published. Required fields are marked *