0
0
Pythonprogramming~5 mins

Object initialization flow in Python

Choose your learning style9 modes available
Introduction
Object initialization flow shows how a new object is created and set up with starting values in a program.
When you want to create a new item with specific starting details, like a new user or product.
When you need to set up an object with default values automatically.
When you want to run some code right after an object is made, like printing a welcome message.
When you want to make sure all objects have the same basic setup steps.
Syntax
Python
class ClassName:
    def __init__(self, param1, param2):
        self.param1 = param1
        self.param2 = param2
The __init__ method runs automatically when you create a new object.
self refers to the new object being created, so you can store values in it.
Examples
Create a Dog object with a name. The name is saved when the object is made.
Python
class Dog:
    def __init__(self, name):
        self.name = name

my_dog = Dog("Buddy")
print(my_dog.name)
Create a Car object with brand and year set during initialization.
Python
class Car:
    def __init__(self, brand, year):
        self.brand = brand
        self.year = year

car1 = Car("Toyota", 2020)
print(car1.brand, car1.year)
Age has a default value if not given when creating the object.
Python
class Person:
    def __init__(self, name, age=30):
        self.name = name
        self.age = age

p = Person("Alice")
print(p.name, p.age)
Sample Program
This program creates a Book object and prints messages during and after initialization.
Python
class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author
        print(f"Book '{self.title}' by {self.author} created.")

my_book = Book("1984", "George Orwell")
print(f"Title: {my_book.title}")
print(f"Author: {my_book.author}")
OutputSuccess
Important Notes
The __init__ method is not a regular method you call; Python calls it automatically when you create an object.
You can add as many parameters as you want to __init__, but the first must always be self.
If you don't define __init__, Python creates an object with no special setup.
Summary
Object initialization flow uses the __init__ method to set up new objects.
self inside __init__ means the new object being created.
You can give default values or require values when making objects.