- Home
- /
- Python__init__ method
Python Tutorial
Introduction
Python Data Types & Oper...
Python Strings
Python Lists
Python Tuples
Python Sets
Python Dictionaries
Conditional Statements
Python Loops
Python Functions
Python Modules
Python OOPS
Advanced Topics
File Handling
- Home
- /
- Python__init__ method
__init__ Method in Python
When you create an object from a class, Python lets you automatically set values for that object using a special method called __init__
.
This method is called the constructor and it runs as soon as the object is created. It’s perfect for setting up values like name, age, category, or anything else your object needs right from the start.
Defining and Using __init__
class Bird:
def __init__(self, name, category):
self.name = name
self.category = category
bird1 = Bird("Parrot", "Tropical Birds")
print(bird1.name, "is a part of", bird1.category)
Output:
Parrot is a part of Tropical Birds
In this example:
__init__()
is automatically called when we createbird1
.self.name = name
assigns the value"Parrot"
tobird1.name
.self.category = category
stores"Tropical Birds"
inbird1.category
.
Modifying Object Properties
You can change values after an object is created:
class Bird:
def __init__(self, name, category):
self.name = name
self.category = category
bird2 = Bird("Sparrow", "Small Birds")
bird2.name = "Robin" # changing property value
print(bird2.name, "is a part of", bird2.category)
Output:
Robin is a part of Small Birds
Deleting an Object
If you no longer need an object, you can delete it using del
. Once deleted, you cannot access its data anymore.
class Bird:
def __init__(self, name, category):
self.name = name
self.category = category
bird3 = Bird("Crow", "Urban Birds")
del bird3 # deleting the object
print(bird3.name)
Output:
NameError: name 'bird3' is not defined
Once deleted, trying to use the object results in an error.
Summary
__init__()
sets up your object the moment it’s created.Use
self
to store values for that specific object.You can change or delete object properties at any time.
This is how Python gives you a clean and organized way to initialize and manage object data.