Python __init__() Method and self Parameter
Python tutorial · PySpark.in
What is __init__() Method?
- The __init__() method is a special method (constructor) in Python classes.
- It is automatically called when a new object of a class is created.
- It is mainly used to initialize (assign values to) the object’s attributes.
In simple terms, it helps to set up the object with initial data when it is created.
Syntax
1class ClassName:
2 def __init__(self, parameters):
3 # initialization code
4 self.attribute = value
▶ Output will appear here.
Example of __init__()
1class Student:
2 def __init__(self, name, roll):
3 self.name = name # initializing instance variable
4 self.roll = roll
5 def display(self):
6 print(f"Name: {self.name}, Roll No: {self.roll}")
7# Creating objects
8s1 = Student("Megha", 101)
9s2 = Student("Ravi", 102)
10# Calling method
11s1.display()
12s2.display()
▶ Output will appear here.
Explanation
- __init__() runs automatically every time an object is created.
- It initializes the object’s attributes like name and roll.
- The self keyword refers to the object being created.
What is self Parameter?
- The self parameter represents the current instance of the class.
- It is used to access variables and methods inside the class.
- You must include self as the first parameter in every instance method, including __init__().
Although you can name it anything, by convention we use self.
Example to Understand self
1class Car:
2 def __init__(self, brand, model):
3 self.brand = brand
4 self.model = model
5 def show(self):
6 print(f"This car is a {self.brand} {self.model}")
7# Creating objects
8car1 = Car("Tesla", "Model S")
9car2 = Car("Toyota", "Fortuner")
10# Calling methods
11car1.show()
12car2.show()
▶ Output will appear here.
How self Works Here
Object | self refers to | Values assigned |
|---|---|---|
car1 | self → car1 | brand="Tesla", model="Model S" |
car2 | self → car2 | brand="Toyota", model="Fortuner" |
Each object keeps its own copy of data, thanks to self.
More Python tutorials
- What is Python and Why is it used for Data Science and Data Engineering?
- How Does Python Work in the Backend? Internal Working of Python
- Top 30 Python Interview Questions for Data Science
- 3-Month Python Roadmap to Excel in Data Science and Machine Learning
- Python Data Types Explained – A Beginner’s Guide
- test
All tutorials · Try the free PySpark compiler · Practice challenges