__init__ in Python: An Overview | Udacity (2024)

Today, a programmer is bound to come across object-oriented programming (OOP) during their career. As a modern programming language, Python provides all the means to implement the object-oriented philosophy. The __init__ method is at the core of OOP and is required to create objects.


In this article, we’ll review the paradigm of object-oriented programming before explaining why and how to use the __init__ method.

What Is Object-Oriented Programming?

Object-oriented programming (OOP) is a programming pattern that consists in defining objects and interacting with them. An object is a collection of complex variables and functions and can be used to represent real entities like a button, an airplane, or a person.

To declare, initialize, and manipulate objects in Python, we use classes. They serve as templates from which objects are created. The following diagram illustrates this idea:

__init__ in Python: An Overview | Udacity (1)

We can see in the above diagram that the dog class contains specific dog characteristics, such as breed and eye color, as well as the abilities to run and walk. Let’s start by defining a class in Python.

What Is a Class?

A class defines and structures all of the objects that are created from it. You can view the class as an object factory. Let’s take the example of a fox terrier—a breed of dog. From an OOP standpoint, you can think of dog as a class that includes a dog’s characteristics such as its breed, or eye color. Since a Fox Terrier is a dog, we can create a dog object that will inherit the characteristics of its class. Classes use methods and constructors to create and define objects.

User-Defined And Special Methods

Methods are functions within a class that are designed to perform a specific task. Python differentiates between user-defined methods, written by the programmer, and special methods that are built into the language. A user-defined method is a function created by the programmer to serve a specific purpose. For instance, a dog class could have a walk() method that the dog object can use. The programmer creates this method and has it perform specific actions.

Special methods are identified by a double underscore at either side of their name, such as __init__. Python uses special methods to enhance the functionality of classes. Most of them work in the background and are called automatically when needed by the program. You cannot call them explicitly. For instance, when you create a new object, Python automatically calls the __new__ method, which in turn calls the __init__ method. The __str__ method is called when you print() an object. On the other hand, user-defined methods, like stefi.run(), are called explicitly.

The Constructor

A constructor is a special method that the program calls upon an object’s creation. The constructor is used in the class to initialize data members to the object. With our dog class example, you can use a constructor to assign dog characteristics to each Fox Terrier object. The special method __init__ is the Python constructor.

With an understanding of object oriented programming and classes, let’s now look at how the __init__ method works within a Python program.

The Importance of Objects in Python

We don’t always see it when we write a program, but objects are central to the way Python works. When we declare a simple variable in Python, an object is created in the background.

If we execute the following bit of code:

breed = "Doberman"


Python uses the str class that contains properties and methods, exactly like the ones you create in your own code, except it’s all happening in the background.

How Does the __init__ Method Work?

The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. The __init__ function is called every time an object is created from a class. The __init__ method lets the class initialize the object’s attributes and serves no other purpose. It is only used within classes.

Create a Class

Let’s begin by creating a class:

class Dog: def __init__(self,dogBreed,dogEyeColor): self.breed = dogBreed self.eyeColor = dogEyeColor...

First, we declare the class Dog using the keyword class. We use the keyword def to define a function or method, such as the __init__ method. As you can see, the __init__ method initializes two attributes: breed and eyeColor.

We’ll now see how to pass these parameters when declaring an object. This is where we need the keyword self to bind the object’s attributes to the arguments received.

Create an Object

Next we’ll create an object, or instance, of the class Dog:

...Tomita = Dog("Fox Terrier","brown")...

When we create the object tomita (which is the dog’s name), we first define the class from which it is created (Dog). We next pass the arguments “Fox Terrier” and “brown,” which correspond to the respective parameters of the __init__ method of the class Dog.

The __init__ method uses the keyword self to assign the values passed as arguments to the object attributes self.breed and self.eyeColor.

Access Object Attributes

To access an attribute of your brand new Fox Terrier object, you can use the dot (.) notation to get the value you need. A print statement helps us demonstrate how this works:

...print("This dog is a",tomita.breed,"and its eyes are",tomita.eyeColor)

Executing the above code gives us the following result:

This dog is a Fox Terrier and its eyes are brown

The program accessed tomita’s attributes and displayed them properly.

The Default __init__ Constructor

In Python, a constructor does not necessarily need parameters passed to it. There can be default parameters. A constructor with no mandatory parameters is called a default constructor. Let’s rewrite our class with a default constructor:

class Dog: def __init__(self, dogBreed="German Shepherd",dogEyeColor="Brown"): self.breed = dogBreed self.eyeColor = dogEyeColor

If a user does not enter any values, the constructor will assign “German Shepherd” and “Brown” as the attributes.

We can now create an instance of Dog without specifying any parameter:

tomita = Dog()

Since there are no arguments to pass, we use empty parentheses after the class name. We can still display the object’s attributes:

print("This dog is a",tomita.breed,"and its eyes are",tomita.eyeColor)

This gives us the following output:

This dog is a German Shepherd and its eyes are Brown

This simple code works perfectly.

Learn To Code With Udacity

The __init__ method is paramount to Python’s object-oriented programming.. In this article, we explained the role of the __init__ method within the context of OOP and class definition. The __init__ method is one of the numerous special methods built into Python, and programmers can use it with or without parameters for each class they create.

Want to really take your coding skills to the next level?

Our Introduction to Programming Nanodegree program is your next step. We’ll teach you the foundations of coding and have you thinking and problem solving like a programmer!

Complete Code Example

Example 1:

class Dog: def __init__(self, dogBreed,dogEyeColor): self.breed = dogBreed self.eyeColor = dogEyeColortomita = Dog("Fox Terrier","brown")print("This dog is a",tomita.breed,"and his eyes are",tomita.eyeColor)

Example 2:

class Dog: def __init__(self): self.nbLegs = 4tomita = Dog()print("This dog has",tomita.nbLegs,"legs")


Example 3:

class Dog: def __init__(self, dogBreed="German Shepherd",dogEyeColor="brown"): self.breed = dogBreed self.eyeColor = dogEyeColortomita = Dog()print("This dog is a",tomita.breed,"and his eyes are",tomita.eyeColor)
__init__ in Python: An Overview | Udacity (2024)

FAQs

What is __ init __ in Python an overview? ›

The python __init__ method is declared within a class and is used to initialize the attributes of an object as soon as the object is formed. While giving the definition for an __init__(self) method, a default parameter, named 'self' is always passed in its argument. This self represents the object of the class itself.

What is the __ init __ Python structure? ›

In Python, the __init__.py file is used to mark a directory as a Python package. It is used to initialize the package when it is imported. The __init__.py file can contain code that will be executed when the package is imported, as well as function definitions and variable assignments.

What does __ init __ return in Python? ›

__init__ method returns a value

The __init__ method of a class is used to initialize new objects, not create them. As such, it should not return any value. Returning None is correct in the sense that no runtime error will occur, but it suggests that the returned value is meaningful, which it is not.

What are the arguments for init in Python? ›

__init__() , which is responsible for the initialization step. This method takes a first argument called self , which holds a reference to the current instance. The method also takes two additional arguments, x and y . These arguments hold initial values for the instance attributes .

Why use __ init __ in Python? ›

The __init__ method, also known as the constructor, is used in Python classes. It is called automatically when an object is created from a class and allows us to initialize the attributes of the object. The name “__init__” is a convention in Python that stands for “initialize.”

What is the difference between __ init __ and init in Python? ›

init__ has no special meaning in Python. It's just a method. __init__ is the magic method that's called automatically on object instantiation.

Is __init__py still needed? ›

This means that __init__.py is now often optional, but it's still useful to structure your initialization code and define how statements like from mypackage import * should work.

Should __init__ py be empty? ›

__init__.py files can be empty: You don't have to put any code in the __init__.py file if you don't need to. An empty __init__.py file is still necessary to mark a directory as a package, but it doesn't have to contain any code.

How to init a Python project? ›

In Visual Studio, select File > New > Project or use the keyboard shortcut Ctrl+Shift+N. The Create a new project screen opens, where you can search and browse templates across different languages.

What does the __init__.py file do? ›

The __init__.py files are required to make Python treat directories containing the file as packages (unless using a namespace package, a relatively advanced feature). This prevents directories with a common name, such as string , from unintentionally hiding valid modules that occur later on the module search path.

Why is self used in Python? ›

To access instance variables: “self” is used to access instance variables within the class. Without “self,” the interpreter would not know which instance variable to access. To create new instance variables: “self” can also be used to create new instance variables dynamically.

How to initialize an object in Python? ›

Initializing Objects Using the __init__() Method

The __init__() method is used in Python classes to initialize newly-created objects. It is automatically called when an object is created using the class constructor. Here's an example of a class with an __init__() method: IPython Shell.

What is the point of init? ›

In object-oriented programming (OOP), the __init__ method is a special method used for initializing instances of a class. It is also known as the constructor method. The primary purpose of the __init__ method is to set up the initial state of an object when it is created.

How do you call __ init __ in Python? ›

The __init__ method in Python is called automatically whenever a new class object is created. This happens using the class name followed by parentheses that contain any arguments required by the __init__ method. In this example, we define a Person class with two attributes name and age.

What is the advantage of init method in Python? ›

Every object could possess its individual values for a class's attributes. The python init method can be adopted to achieve this functionality. It comprises a function object() { [native code] } that permits a class to hold objects with different values.

What is the use of __ init __ file in Python? ›

In Python projects, if you create a file called __init__.py in a directory then Python will treat that directory as a package. A package in Python is a collection of modules (individual . py files) that can be imported into other Python files.

What does __ init __ do in Python Reddit? ›

The __init__ method is an initializer method that is used to initialize the attributes of an object after it is created, whereas the __new__ method is used to create the object.

What does "initialize" mean in Python? ›

Simply speaking, initialization refers to the assignment of an initial value for a variable or data object. Furthermore, it is possible to access the items of a list in Python.

What is Python __main__? ›

__main__ — Top-level script environment

'__main__' is the name of the scope in which top-level code executes.

Top Articles
Latest Posts
Article information

Author: Lidia Grady

Last Updated:

Views: 6241

Rating: 4.4 / 5 (65 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Lidia Grady

Birthday: 1992-01-22

Address: Suite 493 356 Dale Fall, New Wanda, RI 52485

Phone: +29914464387516

Job: Customer Engineer

Hobby: Cryptography, Writing, Dowsing, Stand-up comedy, Calligraphy, Web surfing, Ghost hunting

Introduction: My name is Lidia Grady, I am a thankful, fine, glamorous, lucky, lively, pleasant, shiny person who loves writing and wants to share my knowledge and understanding with you.