Python Constructor (__init__) Explained for Beginners with Examples
Python Constructor (__init__) Explained for Beginners
Introduction
In the previous post, we learned about Python Classes and Objects. Now we will learn about an important concept in OOP called a Constructor.
What is a Constructor?
A constructor is a special function that automatically runs when an object is created from a class.
In Python, the constructor method is called:
__init__()
Basic Example
class Student:
def __init__(self):
print("Constructor is called")
s1 = Student()
When the object s1 is created, the constructor runs automatically.
---Constructor with Parameters
We usually use constructors to assign values to object variables.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
s1 = Student("Ayush", 22)
print(s1.name)
print(s1.age)
Understanding "self"
The self keyword represents the current object.
It allows us to access variables and methods inside the class.
Example:self.name = name
Why Constructors are Important
- Initialize object properties
- Automatically runs when object is created
- Makes code cleaner and organized
- Used in almost every OOP program
Real Example
class Car:
def __init__(self, brand, price):
self.brand = brand
self.price = price
car1 = Car("Tesla", 50000)
print(car1.brand)
print(car1.price)
What You Learned
- What is a constructor
- What is the __init__() method
- How constructors initialize objects
- Using parameters inside constructors
Next Topic
Now that you understand constructors, the next concept is:
Python Inheritance Explained
Inheritance allows one class to use properties of another class.
👋 About the Author
Ayush Gupta
MSc AI/ML Student | Machine Learning & Python Enthusiast
📧 Email:
aygupta9898@gmail.com
Comments
Post a Comment