w3resource

How do you define a constructor in a Python class?

Defining constructors in Python classes

In Python, a constructor is defined using the '__init__()' method within a class. The '__init__()' method is a special method that gets automatically called when an object of the class is created. It is used to initialize the object's attributes and perform any setup tasks required before use.

Syntax: Python constructor class

class ClassName:
    def __init__(self, parameter1, parameter2, ...):
        # Initialization code
        self.parameter1 = parameter1
        self.parameter2 = parameter2
        # ...

Where -

  • '__init()__' is the constructor method's name. It always starts and ends with two underscores ('__'), which indicates that it's a special method in Python.
  • The first parameter of the '__init()__' method is always 'self', which refers to the instance of the class being created. It is automatically passed to the constructor when the object is instantiated.
  • After 'self', you can define any other parameters needed to initialize the object's attributes. The parameters are used to set the initial values of the object's attributes.

Inside the '__init()__' method, you can use the provided parameters to initialize the object's attributes by assigning values to them using the 'self' keyword.

Example: Python class with constructor

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

In this example, the "Student" class has a constructor 'init()' that takes two parameters 'name' and 'age'. When an instance of the "Student" class is created, the constructor will automatically be called, and the provided 'name' and 'age' values will be used to initialize the object's attributes.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-interview/how-do-you-define-a-constructor-in-a-python-class.php