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
Selected Reading
How to create instance Objects using __init__ in Python?
The __init__() method is a special method in Python classes that automatically runs when you create a new instance of a class. It's commonly called a constructor and allows you to initialize object attributes with specific values.
Basic __init__() Method
Here's how to define a simple __init__() method ?
class Student:
def __init__(self):
self.name = "Unknown"
self.age = 0
self.grades = []
# Create an instance
student1 = Student()
print(f"Name: {student1.name}")
print(f"Age: {student1.age}")
print(f"Grades: {student1.grades}")
Name: Unknown Age: 0 Grades: []
__init__() Method with Parameters
You can pass arguments to __init__() to customize object initialization ?
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
self.grades = []
# Create instances with different values
student1 = Student("Alice", 20)
student2 = Student("Bob", 22)
print(f"Student 1: {student1.name}, Age: {student1.age}")
print(f"Student 2: {student2.name}, Age: {student2.age}")
Student 1: Alice, Age: 20 Student 2: Bob, Age: 22
Complex Number Example
Here's a practical example creating a Complex number class ?
class Complex:
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
def display(self):
return f"{self.r} + {self.i}i"
# Create complex number instances
x = Complex(4.0, -6.5)
y = Complex(2.0, 3.0)
print(f"Complex number x: {x.display()}")
print(f"Real part: {x.r}, Imaginary part: {x.i}")
print(f"Complex number y: {y.display()}")
Complex number x: 4.0 + -6.5i Real part: 4.0, Imaginary part: -6.5 Complex number y: 2.0 + 3.0i
__init__() with Default Parameters
You can provide default values to make some parameters optional ?
class Car:
def __init__(self, brand, model, year=2023):
self.brand = brand
self.model = model
self.year = year
def info(self):
return f"{self.year} {self.brand} {self.model}"
# Create cars with and without year parameter
car1 = Car("Toyota", "Camry")
car2 = Car("Honda", "Civic", 2020)
print(car1.info())
print(car2.info())
2023 Toyota Camry 2020 Honda Civic
Key Points
- The
__init__()method is called automatically when creating an object - The first parameter must always be
self - You can have multiple parameters with default values
- Use
self.attributeto set instance variables - Each object gets its own copy of instance variables
Conclusion
The __init__() method is essential for object initialization in Python. It allows you to set up initial state and customize objects during creation, making your classes more flexible and useful.
Advertisements
