Python Constructor Tutorial
Table of Content:-
- What is a Constructor?
- Types of Constructors
- I. Default Constructor
- II. Parameterized Constructor
- III. Constructors with Default Parameter Values
- Practical Example: Bank Account Class with Constructor
In Python, constructors are special methods used to initialize the state of an object when it’s created. Constructors allow you to set the initial values for the object’s attributes and perform any setup or initialization. In Python, constructors are defined using the __init__ method within a class.
Here’s a detailed look at constructors, including types and examples.
1) What is a Constructor?
A constructor is a method that is automatically called when a new instance (object) of a class is created. In Python, the constructor is defined with the method name __init__. This method initializes the object’s attributes and prepares it for use.
Syntax of a Constructor
class ClassName:
def __init__ (self, parameters):
# Initialization code
self. attribute = value
- __init__: This is the constructor method name.
- self: Represents the instance of the class. It’s used to access attributes and methods of the class within the constructor.
- parameters: These are additional values that you want to pass while creating an instance.
2) Types of Constructors
There are two main types of constructors in Python:
- Default Constructor: A constructor with no parameters (other than self).
- Parameterized Constructor: A constructor with one or more parameters, allowing specific values to be passed at object creation.
I. Default Constructor
A default constructor initializes an object without requiring any parameters from the user. It’s mostly used when default values for the attributes are sufficient.
Example of a Default Constructor
class Animal:
def __init__(self): # Default constructor with no parameters
self.name = "Unknown"
self. species = "Unknown"
def display(self):
print (f"Name: {self.name}, Species: {self. species}")
# Create an instance of Animal using the default constructor
animal1 = Animal ()
animal1.display()
Output:
Name: Unknown, Species: Unknown
In this example, the Animal class has a default constructor that sets name and species attributes to default values “Unknown”.
II. Parameterized Constructor
A parameterized constructor allows parameters to be passed, which can be used to initialize the object’s attributes with specific values provided during object creation.
Example of a Parameterized Constructor
class Animal:
def __init__ (self, name, species): # Parameterized constructor
self.name = name
self. species = species
def display(self):
print (f"Name: {self.name}, Species: {self. species}")
# Create instances of Animal with different names and species
animal1 = Animal ("Lion", "Mammal")
animal2 = Animal ("Parrot", "Bird")
animal1.display()
animal2.display()
Output:
Name: Lion, Species: Mammal
Name: Parrot, Species: Bird
In this case, the Animal class constructor accepts two parameters, name and species, which are used to initialize the respective attributes.
III. Constructors with Default Parameter Values
You can also provide default values to parameters in a parameterized constructor. This makes it possible to create objects without passing all arguments, as the missing ones will take the default values.
Example with Default Parameter Values
class Animal:
def __init__ (self, name="Unknown", species="Unknown"):
self.name = name
self. species = species
def display(self):
print (f"Name: {self.name}, Species: {self. species}")
# Using default values
animal1 = Animal ()
# Passing only the name, species will take the default value
animal2 = Animal(name="Dog")
animal1.display()
animal2.display()
Output:
Name: Unknown, Species: Unknown
Name: Dog, Species: Unknown
Here, if an argument isn’t provided, the constructor uses “Unknown” as the default value for name and species.
Practical Example: Bank Account Class with Constructor
Let’s see a practical example with a BankAccount class, where we set up initial balance and account holder name using a constructor.
class BankAccount:
def __init__ (self, account_holder, initial_balance=0):
self. account_holder = account_holder
self. balance = initial_balance
def deposit (self, amount):
self. balance += amount
print (f"Deposited {amount}. New balance: {self. balance}")
def withdraw (self, amount):
if amount > self. balance:
print ("Insufficient funds!")
else:
self. balance -= amount
print (f"Withdrew {amount}. New balance: {self. balance}")
# Creating an account with an initial balance
account1 = BankAccount ("Alice", 1000)
account1.deposit(500)
account1.withdraw(300)
# Creating an account without an initial balance (defaults to 0)
account2 = BankAccount("Bob")
account2.deposit(200)
account2.withdraw(50)
Output:
Deposited 500. New balance: 1500
Withdrew 300. New balance: 1200
Deposited 200. New balance: 200
Withdrew 50. New balance: 150
In this example:
- The BankAccount constructor takes account_holder and initial_balance as parameters.
- If no initial_balance is provided, it defaults to 0.
Summary
- Constructor in Python is defined by the __init__ method.
- Default Constructor: No parameters other than self. Sets default values.
- Parameterized Constructor: Accepts parameters to initialize specific values.
- Constructors make object initialization flexible and set the stage for the object’s state.
By using constructors, you can ensure that objects are created with the proper initial state, which is crucial for designing robust classes and applications.