June 24, 2024

Tirth's Blog

My technical notes

__init__() function in Python

2 min read

In Python, the __init__ function is a special method that is automatically called when an object is created from a class. It stands for “initialize” and is commonly used to set up the initial state of an object by assigning values to its attributes or performing any necessary setup operations.

The __init__ method is defined within a class and takes at least one parameter, typically named self, which refers to the instance of the class being created. It allows you to access and manipulate the attributes and methods of the object within the __init__ function.

Here’s an example of a simple class with an __init__ method:

pythonCopy codeclass MyClass:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hello, my name is {self.name} and I'm {self.age} years old.")

# Creating an object of MyClass
obj = MyClass("John", 25)

# Calling the greet method
obj.greet()

In this example, the __init__ method takes two parameters, name and age. When an object of the MyClass is created, the __init__ method is automatically invoked and assigns the provided values to the name and age attributes of the object. The greet method can then access these attributes using self and perform some action.

Output:

Hello, my name is John and I'm 25 years old.

By using the __init__ method, you can ensure that the necessary attributes are initialized whenever an object is created from the class, providing a convenient way to set up the initial state of objects.

More Stories

Leave a Reply

Your email address will not be published. Required fields are marked *

You may have missed

Copyright © All rights reserved. | Newsphere by AF themes.