In this article, we will learn about the constructor function of a class in Python. This is the next article after Building class and creating object in Python. It would be best if you read this article first to understand the fundamental concepts about classes and objects in Python before learning about the init() function in Python.
1. The init() function in Python
The __init__()
function is the constructor function of a class in Python. All classes in Python have __init__()
function. The constructor function is invoked when an object of a class is instantiated. Its purpose is to assign values to the attributes of the object or perform some operations during the object’s creation.
The syntax of the __init__()
function in Python:
def __init__(self, [parameter1, parameter2,...]):
# Body of __init__()
Where,
- def is the keyword to declare a function in Python
- __init__() is the name of the constructor function
- self is the first parameter of the __init__() function. This is a reference to the current object of the class. This is how you access the variables that belong to that class.
- [parameter1, parameter2,…] are optional parameters. They are values to assign to the attributes of the object being created.
The example below creates a Cat class with the class attribute species and the attributes of each object are name and color.
class Cat:
# class attribute
species = "cat"
# constructor of class Cat
# instance attribute
def __init__(self, cat_name, cat_color):
self.name = cat_name
self.color = cat_color
# Methods of Cat class
def catInfo(self):
print(self.name, "cat has", self.color, "color")
def catchMouse(self):
print(self.name, "catch mouse.")
def sleep(self):
print(self.name, "take a nap.")
tom = Cat("Tom", "grey and white")
tom.catInfo()
mycat = Cat("Milk", "black and white")
mycat.catInfo()
Result
Tom cat has grey and white color
Milk cat has black and white color
In the Cat class, the species attribute is the attribute of the class. The attribute of the class will have the same value for all objects of the class. The name and color attributes are the attributes of the object. The attributes of each object created from the same class may be different.
We can delete the attributes of the object with the del keyword.
class Cat:
# class attribute
species = "cat"
# constructor of class Cat
# instance attribute
def __init__(self, cat_name, cat_color):
self.name = cat_name
self.color = cat_color
# Methods of Cat class
def catInfo(self):
print(self.name, "cat has", self.color, "color")
def catchMouse(self):
print(self.name, "catch mouse.")
def sleep(self):
print(self.name, "take a nap.")
tom = Cat("Tom", "grey and white")
print("name of tom:", tom.name)
del tom.name
print("name of tom:", tom.name)
Result
name of tom: Tom
Traceback (most recent call last):
File "c:\python-examples\example.py", line 22, in <module>
print("name of tom:", tom.name)
AttributeError: 'Cat' object has no attribute 'name'
Note: Python does not allow deleting class attributes.
class Cat:
# class attribute
species = "cat"
# constructor of class Cat
# instance attribute
def __init__(self, cat_name, cat_color):
self.name = cat_name
self.color = cat_color
# Methods of Cat class
def catInfo(self):
print(self.name, "cat has", self.color, "color")
def catchMouse(self):
print(self.name, "catch mouse.")
def sleep(self):
print(self.name, "take a nap.")
tom = Cat("Tom", "grey and white")
del tom.species
Result
Traceback (most recent call last):
File "c:\python-examples\example.py", line 20, in <module>
del tom.species
AttributeError: species
2. Types of constructors in Python
In Python, there are 3 types of constructors:
- Default constructor
- Non-parameterized constructor
- Parameterized constructor
2.1. Default constructor
When defining a class, if we do not define the __init__() function, Python will create this function for us. This constructor is called the default constructor. The default constructor will not perform any task.
Note: The default constructor will be automatically added to our class when compiled by Python. If we have defined a constructor in the class, the default constructor will not be added to the class.
class Cat:
# class attribute
species = "cat"
# Methods of Cat class
def catchMouse(self):
print("Catch mouse.")
def sleep(self):
print("Take a nap.")
tom = Cat()
tom.catchMouse()
tom.sleep()
Result
Catch mouse.
Take a nap.
2.2. Non-parameterized constructor
The ___init__ function with no parameters other than the self parameter is known as a non-parameterized constructor. This type of constructor helps to create objects with default values. This means that newly created objects are completely identical.
class Cat:
# class attribute
species = "cat"
# non-parameterized constructor
def __init__(self):
self.name = "Tom"
self.color = "grey and white"
# Methods of Cat class
def catInfo(self):
print(self.name, "cat has", self.color, "color")
# create objects of Cat class with non-parameterized constructor
tom1 = Cat()
print("Info of tom1:")
tom1.catInfo()
tom2 = Cat()
print("Info of tom2:")
tom2.catInfo()
tom2.name = "Tom2"
tom2.color = "black and white"
print("Info of tom2 after changed:")
tom2.catInfo()
Result
Info of tom1:
Tom cat has grey and white color
Info of tom2:
Tom cat has grey and white color
Info of tom2 after changed:
Tom2 cat has black and white color
2.3. Parameterized constructor
This is the __init__() function that has parameters other than the self parameter. It is called the parameterized constructor. With parameterized constructor, we can pass different values when creating objects of a class.
class Cat:
# class attribute
species = "cat"
# parameterized constructor
def __init__(self, cat_name, cat_color):
self.name = cat_name
self.color = cat_color
# Methods of Cat class
def catInfo(self):
print(self.name, "cat has", self.color, "color")
# create objects of Cat class with parameterized constructor
tom = Cat("Tom", "grey and white")
tom.catInfo()
mycat = Cat("Milk", "black and white")
mycat.catInfo()
Result
Tom cat has grey and white color
Milk cat has black and white color
2.4. Constructor function with default values
Python allows us to create a constructor function with default values. The constructor function will use default values if no arguments are passed during object creation.
class Cat:
# parameterized constructor
def __init__(self, cat_name, cat_color="grey and white", cat_weight=3.9):
self.name = cat_name
self.color = cat_color
self.weight = cat_weight
# Methods of Cat class
def catInfo(self):
print(self.name, "cat has", self.color, "color, weight", self.weight)
# create objects of Cat class with parameterized constructor
tom = Cat("Tom")
tom.catInfo()
mycat = Cat("Milk", "black and white")
mycat.catInfo()
myfriendcat = Cat("MeoMeo", "black and white", 4.5)
myfriendcat.catInfo()
Result
Tom cat has grey and white color, weight 3.9
Milk cat has black and white color, weight 3.9
MeoMeo cat has black and white color, weight 4.5
Note: To avoid errors, you need to place default value parameters to the right of parameters that do not have default values.
3. Notes for using the __init()__ function in Python
3.1. Python does not allow more than one __init__() function in a class
class Cat:
# constructor with 1 parameter
def __init__(self, cat_name):
self.name = cat_name
# constructor with 2 parameters
def __init__(self, cat_name, cat_color):
self.name = cat_name
self.color = cat_color
# Methods of Cat class
def catInfo(self):
print(self.name, "cat has", self.color, "color")
# create objects of Cat class
tom = Cat("Tom")
tom.catInfo()
Result
Traceback (most recent call last):
File "c:\python-examples\example.py", line 15, in <module>
tom = Cat("Tom")
TypeError: Cat.__init__() missing 1 required positional argument: 'cat_color'
3.2. Python does not allow the __init__() function to return any value
class Cat:
# constructor with 2 parameters and return
def __init__(self, cat_name, cat_color):
self.name = cat_name
self.color = cat_color
return True
# Methods of Cat class
def catInfo(self):
print(self.name, "cat has", self.color, "color")
# create objects of Cat class
tom = Cat("Tom", "grey and white")
tom.catInfo()
Result
Traceback (most recent call last):
File "c:\python-examples\example.py", line 13, in <module>
tom = Cat("Tom", "grey and white")
TypeError: __init__() should return None, not 'bool'