In this tutorial we will learn how to take only a single character as an input in python with some cool and easy examples. In many situations, you might have to come up with this type of requirements.
Constructors in Python
A constructor is a special type of method (function) which is used to initialize the instance members of the class.
Constructor definition is executed when we create the object of this class. Constructors also verify that there are enough resources for the object to perform any start-up task.
Syntax of constructor declaration :
def __init__(self): # body of the constructor
Creating the constructor in python:
In Python, the method the __init__() simulates the constructor of the class. This method is called when the class is instantiated. It accepts the self-keyword as a first argument which allows accessing the attributes or method of the class.
We can pass any number of arguments at the time of creating the class object, depending upon the __init__() definition. It is mostly used to initialize the class attributes. Every class must have a constructor, even if it simply relies on the default constructor.
Types of constructors :
- default constructor: The default constructor is a simple constructor which doesn’t accept any arguments. Its definition has only one argument which is a reference to the instance being constructed.
- parameterized constructor: constructor with parameters is known as parameterized constructor. The parameterized constructor takes its first argument as a reference to the instance being constructed known as self and the rest of the arguments are provided by the programmer.
Constructor Example
Let us define the constructor in the Employee class to initialize name and age as instance variables. We can then access these attributes of its object.
Python Constructor Implementation Code:
class Employee: 'Common base class for all employees' def __init__(self): self.name = "Bhavana" self.age = 24 e1 = Employee() print ("Name: {}".format(e1.name)) print ("age: {}".format(e1.age))
It will produce the following output −
Name: Bhavana age: 24
Parameterized Constructor:
For the above Employee class, each object we declare will have same value for its instance variables name and age. To declare objects with varying attributes instead of the default, define arguments for the __init__() method. (A method is nothing but a function defined inside a class.)
Example
In this example, the __init__() constructor has two formal arguments. We declare Employee objects with different values −
class Employee: 'Common base class for all employees' def __init__(self, name, age): self.name = name self.age = age e1 = Employee("Bhavana", 24) e2 = Employee("Bharat", 25) print ("Name: {}".format(e1.name)) print ("age: {}".format(e1.age)) print ("Name: {}".format(e2.name)) print ("age: {}".format(e2.age))
It will produce the following output −
Name: Bhavana age: 24 Name: Bharat age: 25