Python __init__() Method and self Parameter

Python tutorial · PySpark.in

What is __init__() Method?

In simple terms, it helps to set up the object with initial data when it is created.

Syntax

PLAINTEXT
1class ClassName:
2 def __init__(self, parameters):
3 # initialization code
4 self.attribute = value
▶ Output will appear here.

Example of __init__()

PYTHON
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

What is self Parameter?

Although you can name it anything, by convention we use self.

Example to Understand self

PYTHON
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

All tutorials · Try the free PySpark compiler · Practice challenges