[ Web Proxy ]
URL:
Viewing: https://www.pythontutorial.net/python-oop/python-__init__/ [Back]  [Original]

Python __init__
Skip to content

Python __init__

Summary: in this tutorial, you’ll learn how to use the Python __init__() method to initialize object’s attributes.

Introduction to the Python __init__() method #

When you create a new object of a class, Python automatically calls the __init__() method to initialize the object’s attributes.

Unlike regular methods, the __init__() method has two underscores (__) on each side. Therefore, the __init__() is often called dunder init. The name comes abbreviation of the double underscores init.

The double underscores at both sides of the __init__() method indicate that Python will use the method internally. In other words, you should not explicitly call this method.

Since Python will automatically call the __init__() method immediately after creating a new object, you can use the __init__() method to initialize the object’s attributes.

The following defines the Person class with the __init__() method:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age


person = Person('John', 25)
print(f"I'm {person.name}. I'm {person.age} years old.")
Code language: Python (python)

Try it

Output:

I'm John. I'm 25 years old.Code language: JavaScript (javascript)

When you create an instance of the Person class, Python performs two things:

Note that the __init__ method doesn’t create the object but only initializes the object’s attributes. Hence, the __init__() is not a constructor.

If the __init__ has parameters other than the self, you need to pass the corresponding arguments when creating a new object like the example above. Otherwise, you’ll get an error.

The __init__ method with default parameters #

The __init__() method’s parameters can have default values. For example:

class Person:
    def __init__(self, name, age=22):
        self.name = name
        self.age = age


person = Person('John')
print(f"I'm {person.name}. I'm {person.age} years old.")

Try it

Output:

I'm John. I'm 22 years old.Code language: JavaScript (javascript)

In this example, the age parameter has a default value of 22. Because we don’t pass an argument to the Person(), the age uses the default value.

Summary #

Quiz #

Was this tutorial helpful ?
Yes No
Search …:

Classes & Objects

Special Methods

Property

Single Inheritance

Enumerations

SOLID Principles

Multiple Inheritance

Descriptors

Meta Programming

Exceptions

Copyright © 2021 - Present, By Python Tutorial. All Rights Reserved.


Web Proxy Viewer  |  New URL  |  Original Page