Select Page

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:

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 = dogEyeColor

tomita = 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 = 4

tomita = 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 = dogEyeColor

tomita = Dog()

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