Constructor in Python
- Get link
- X
- Other Apps
Constructor in Python
In Python, a constructor is a special method that is automatically called when an object is created. It is used to initialize the object's attributes and perform any necessary setup.
The constructor method in Python is called __init__(). It takes the self parameter, which refers to the object being created, and any other parameters needed to initialize the object's attributes.
Here's an example of how to define a constructor in a Python class:
class Person: def __init__(self, name, age): self.name = name self.age = age print('Person created') # Create a Person object p = Person('Alice', 25) # Print the person's name and age print(p.name) # Output: Alice print(p.age) # Output: 25
In the example above, we define a Person class with a constructor that takes two parameters, name and age, and initializes the corresponding attributes of the object using the self parameter. We also print a message when a Person object is created, just to show that the constructor is called automatically.
When we create a Person object p with the arguments 'Alice' and 25, the constructor is called automatically with self set to the new object being created. The constructor initializes the name and age attributes of the object, and the object is returned and assigned to the variable p.
We can access the name and age attributes of the Person object p using the dot notation (p.name and p.age, respectively).
Constructors can be useful for setting up the initial state of objects and performing any necessary setup. They can also be used to validate input parameters and raise exceptions if necessary.
Happy Learning!! Happy Coding!!
- Get link
- X
- Other Apps
Comments