What is a constructor in Python?
Python Constructors: Initializing Objects with __init__()
In Python, a constructor is a special method that automatically calls when an object is created. It is used to initialize the object's attributes and perform any setup tasks required before use.
Python's constructor method is defined using the init() function. The init() method takes the 'self ' parameter, which refers to the instance of the class being created and any other parameters needed to initialize the object's attributes. Inside the constructor, you can set the initial values for the object's attributes based on the arguments passed to the constructor.
Here's an example of a simple constructor in Python:
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
# Creating an instance of the Person class and calling the constructor
student1 = Student("Viola", 14)
student2 = Student("Anders", 15)
# Accessing the attributes of the objects
print(student1.name) # Output: Viola
print(student1.age) # Output: 14
print(student2.name) # Output: Anders
print(student2.age) # Output: 15
In this example, the "Student" class has a constructor 'init()' that takes two parameters 'name' and 'age'. When we create instances 'student1' and 'student2' of the "Student" class, the constructor is automatically called with the arguments "Viola", 14 and "Anders", 15, respectively. Inside the constructor, we assign these values to the 'name' and 'age' attributes of the objects.
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/what-is-a-constructor-in-python.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics