Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is difference between self and __init__ methods in python Class?
In Python classes, self and __init__ serve different but complementary purposes. Understanding their roles is essential for object-oriented programming in Python.
What is self?
The self parameter represents the instance of a class. It allows you to access the attributes and methods of the class from within its methods. When you call a method on an object, Python automatically passes the object itself as the first argument.
Example
class Student:
def set_name(self, name):
self.name = name # self refers to the current instance
def get_name(self):
return self.name # self accesses the instance attribute
student1 = Student()
student1.set_name("Alice")
print(student1.get_name())
Alice
What is __init__ method?
The __init__ method is a special method called a constructor. It is automatically called when an object is created from a class and allows you to initialize the attributes of the class with specific values.
Example
class Student:
def __init__(self, name, age):
self.name = name # Initialize name attribute
self.age = age # Initialize age attribute
def display_info(self):
return f"Name: {self.name}, Age: {self.age}"
student1 = Student("Bob", 20)
print(student1.display_info())
Name: Bob, Age: 20
Practical Example
Let's find the cost of a rectangular field with breadth (120), length (160), costing 2000 rupees per square unit ?
class Rectangle:
def __init__(self, length, breadth, unit_cost=0):
self.length = length
self.breadth = breadth
self.unit_cost = unit_cost
def get_area(self):
return self.length * self.breadth
def calculate_cost(self):
area = self.get_area()
return area * self.unit_cost
# Create rectangle: breadth=120, length=160, cost=2000 per sq unit
r = Rectangle(160, 120, 2000)
print("Area of Rectangle: %s sq units" % (r.get_area()))
print("Cost of rectangular field: Rs.%s" % (r.calculate_cost()))
Area of Rectangle: 19200 sq units Cost of rectangular field: Rs.38400000
Key Differences
| Aspect | self | __init__ |
|---|---|---|
| Purpose | Reference to instance | Constructor method |
| When used | In all instance methods | During object creation |
| Function | Access attributes/methods | Initialize object state |
| Required | First parameter in methods | Optional (but commonly used) |
Conclusion
self is a reference to the current instance used in all methods, while __init__ is a constructor method that initializes object attributes. Both work together to create and manage objects in Python classes.
