0
0
Pythonprogramming~5 mins

__init__ method behavior in Python

Choose your learning style9 modes available
Introduction

The __init__ method sets up a new object when you create it. It helps give the object its starting values.

When you want to give an object its own information right after making it.
When you need to prepare or organize data inside an object automatically.
When you want to make sure every new object has certain details filled in.
When you want to customize objects differently each time you create one.
When you want to run some setup steps as soon as an object is made.
Syntax
Python
class ClassName:
    def __init__(self, parameter1, parameter2):
        self.attribute1 = parameter1
        self.attribute2 = parameter2

self means the object itself and is always the first parameter.

You can add as many parameters as you want to give different starting values.

Examples
This example sets the dog's name when you create it.
Python
class Dog:
    def __init__(self, name):
        self.name = name
This example sets the car's make and year during creation.
Python
class Car:
    def __init__(self, make, year):
        self.make = make
        self.year = year
This example shows a default value for age if none is given.
Python
class Person:
    def __init__(self, name, age=0):
        self.name = name
        self.age = age
Sample Program

This program creates a Book object with a title and author, then prints them.

Python
class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

my_book = Book("The Sun", "Alice")
print(f"Title: {my_book.title}")
print(f"Author: {my_book.author}")
OutputSuccess
Important Notes

The __init__ method does not return anything; it just sets up the object.

If you don't write an __init__ method, Python makes a default one that does nothing.

You can use self to store values that belong to the object and can be used later.

Summary

The __init__ method runs automatically when you create an object.

It helps give each object its own starting information.

You use self to keep data inside the object.