- Python Basics
- Python - Home
- Python - Overview
- Python - History
- Python - Features
- Python vs C++
- Python - Hello World Program
- Python - Application Areas
- Python - Interpreter
- Python - Environment Setup
- Python - Virtual Environment
- Python - Basic Syntax
- Python - Variables
- Python - Data Types
- Python - Type Casting
- Python - Unicode System
- Python - Literals
- Python - Operators
- Python - Arithmetic Operators
- Python - Comparison Operators
- Python - Assignment Operators
- Python - Logical Operators
- Python - Bitwise Operators
- Python - Membership Operators
- Python - Identity Operators
- Python - Operator Precedence
- Python - Comments
- Python - User Input
- Python - Numbers
- Python - Booleans
- Python Control Statements
- Python - Control Flow
- Python - Decision Making
- Python - If Statement
- Python - If else
- Python - Nested If
- Python - Match-Case Statement
- Python - Loops
- Python - for Loops
- Python - for-else Loops
- Python - While Loops
- Python - break Statement
- Python - continue Statement
- Python - pass Statement
- Python - Nested Loops
- Python Functions & Modules
- Python - Functions
- Python - Default Arguments
- Python - Keyword Arguments
- Python - Keyword-Only Arguments
- Python - Positional Arguments
- Python - Positional-Only Arguments
- Python - Arbitrary Arguments
- Python - Variables Scope
- Python - Function Annotations
- Python - Modules
- Python - Built in Functions
- Python Strings
- Python - Strings
- Python - Slicing Strings
- Python - Modify Strings
- Python - String Concatenation
- Python - String Formatting
- Python - Escape Characters
- Python - String Methods
- Python - String Exercises
- Python Lists
- Python - Lists
- Python - Access List Items
- Python - Change List Items
- Python - Add List Items
- Python - Remove List Items
- Python - Loop Lists
- Python - List Comprehension
- Python - Sort Lists
- Python - Copy Lists
- Python - Join Lists
- Python - List Methods
- Python - List Exercises
- Python Tuples
- Python - Tuples
- Python - Access Tuple Items
- Python - Update Tuples
- Python - Unpack Tuples
- Python - Loop Tuples
- Python - Join Tuples
- Python - Tuple Methods
- Python - Tuple Exercises
- Python Sets
- Python - Sets
- Python - Access Set Items
- Python - Add Set Items
- Python - Remove Set Items
- Python - Loop Sets
- Python - Join Sets
- Python - Copy Sets
- Python - Set Operators
- Python - Set Methods
- Python - Set Exercises
- Python Dictionaries
- Python - Dictionaries
- Python - Access Dictionary Items
- Python - Change Dictionary Items
- Python - Add Dictionary Items
- Python - Remove Dictionary Items
- Python - Dictionary View Objects
- Python - Loop Dictionaries
- Python - Copy Dictionaries
- Python - Nested Dictionaries
- Python - Dictionary Methods
- Python - Dictionary Exercises
- Python Arrays
- Python - Arrays
- Python - Access Array Items
- Python - Add Array Items
- Python - Remove Array Items
- Python - Loop Arrays
- Python - Copy Arrays
- Python - Reverse Arrays
- Python - Sort Arrays
- Python - Join Arrays
- Python - Array Methods
- Python - Array Exercises
- Python File Handling
- Python - File Handling
- Python - Write to File
- Python - Read Files
- Python - Renaming and Deleting Files
- Python - Directories
- Python - File Methods
- Python - OS File/Directory Methods
- Python - OS Path Methods
- Object Oriented Programming
- Python - OOPs Concepts
- Python - Classes & Objects
- Python - Class Attributes
- Python - Class Methods
- Python - Static Methods
- Python - Constructors
- Python - Access Modifiers
- Python - Inheritance
- Python - Polymorphism
- Python - Method Overriding
- Python - Method Overloading
- Python - Dynamic Binding
- Python - Dynamic Typing
- Python - Abstraction
- Python - Encapsulation
- Python - Interfaces
- Python - Packages
- Python - Inner Classes
- Python - Anonymous Class and Objects
- Python - Singleton Class
- Python - Wrapper Classes
- Python - Enums
- Python - Reflection
- Python Errors & Exceptions
- Python - Syntax Errors
- Python - Exceptions
- Python - try-except Block
- Python - try-finally Block
- Python - Raising Exceptions
- Python - Exception Chaining
- Python - Nested try Block
- Python - User-defined Exception
- Python - Logging
- Python - Assertions
- Python - Built-in Exceptions
- Python Multithreading
- Python - Multithreading
- Python - Thread Life Cycle
- Python - Creating a Thread
- Python - Starting a Thread
- Python - Joining Threads
- Python - Naming Thread
- Python - Thread Scheduling
- Python - Thread Pools
- Python - Main Thread
- Python - Thread Priority
- Python - Daemon Threads
- Python - Synchronizing Threads
- Python Synchronization
- Python - Inter-thread Communication
- Python - Thread Deadlock
- Python - Interrupting a Thread
- Python Networking
- Python - Networking
- Python - Socket Programming
- Python - URL Processing
- Python - Generics
- Python Libraries
- NumPy Tutorial
- Pandas Tutorial
- SciPy Tutorial
- Matplotlib Tutorial
- Django Tutorial
- OpenCV Tutorial
- Python Miscellenous
- Python - Date & Time
- Python - Maths
- Python - Iterators
- Python - Generators
- Python - Closures
- Python - Decorators
- Python - Recursion
- Python - Reg Expressions
- Python - PIP
- Python - Database Access
- Python - Weak References
- Python - Serialization
- Python - Templating
- Python - Output Formatting
- Python - Performance Measurement
- Python - Data Compression
- Python - CGI Programming
- Python - XML Processing
- Python - GUI Programming
- Python - Command-Line Arguments
- Python - Docstrings
- Python - JSON
- Python - Sending Email
- Python - Further Extensions
- Python - Tools/Utilities
- Python - GUIs
- Python Useful Resources
- Python Compiler
- NumPy Compiler
- Matplotlib Compiler
- SciPy Compiler
- Python - Questions & Answers
- Python - Online Quiz
- Python - Programming Examples
- Python - Quick Guide
- Python - Useful Resources
- Python - Discussion
Python - Constructors
Python constructor is an instance method in a class, that is automatically called whenever a new object of the class is created. The constructor's role is to assign value to instance variables as soon as the object is declared.
Python uses a special method called __init__() to initialize the instance variables for the object, as soon as it is declared.
Creating a constructor in Python
The __init__() method acts as a constructor. It needs a mandatory argument named self, which is the reference to the object.
def __init__(self, parameters): #initialize instance variables
The __init__() method as well as any instance method in a class has a mandatory parameter, self. However, you can give any name to the first parameter, not necessarily self.
Types of Constructor in Python
Python has two types of constructor −
- Default Constructor
- Parameterized Constructor
Default Constructor in Python
The Python constructor which does not accept any parameter other than self is called as default 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 through its object.
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
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.
Parameterized Constructor
If a constructor is defined with multiple parameters along with self is called as parameterized constructor.
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
You can also assign default values to the formal arguments in the constructor so that the object can be instantiated with or without passing parameters.
class Employee: 'Common base class for all employees' def __init__(self, name="Bhavana", age=24): self.name = name self.age = age e1 = Employee() 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
Python - Instance Methods
In addition to the __init__() constructor, there may be one or more instance methods defined in a class. A method with self as one of the formal arguments is called instance method, as it is called by a specific object.
Example
In the following example a displayEmployee() method has been defined as an instance method. It returns the name and age attributes of the Employee object that calls the method.
class Employee: def __init__(self, name="Bhavana", age=24): self.name = name self.age = age def displayEmployee(self): print ("Name : ", self.name, ", age: ", self.age) e1 = Employee() e2 = Employee("Bharat", 25) e1.displayEmployee() e2.displayEmployee()
It will produce the following output −
Name : Bhavana , age: 24 Name : Bharat , age: 25
You can add, remove, or modify attributes of classes and objects at any time −
# Add a 'salary' attribute emp1.salary = 7000 # Modify 'name' attribute emp1.name = 'xyz' # Delete 'salary' attribute del emp1.salary
Instead of using the normal statements to access attributes, you can use the following functions −
The getattr(obj, name[, default]) − to access the attribute of object.
The hasattr(obj,name) − to check if an attribute exists or not.
The setattr(obj,name,value) − to set an attribute. If attribute does not exist, then it would be created.
The delattr(obj, name) − to delete an attribute.
# Returns true if 'salary' attribute exists print (hasattr(e1, 'salary')) # Returns value of 'name' attribute print (getattr(e1, 'name')) # Set attribute 'salary' at 8 setattr(e1, 'salary', 7000) # Delete attribute 'age' delattr(e1, 'age')
It will produce the following output −
False Bhavana
Python Multiple Constructors
As mentioned earlier, we define the __init__() method to create a constructor. However, unlike other programming languages like C++ and Java, Python does not allow multiple constructors.
If you try to create multiple constructors, Python will not throw an error, but it will only consider the last __init__() method in your class. Its previous definition will be overridden by the last one.
But, there is a way to achieve similar functionality in Python. We can overload constructors based on the type or number of arguments passed to the __init__() method. This will allow a single constructor method to handle various initialization scenarios based on the arguments provided.
Example
The following example shows how to achieve functionality similar to multiple constructors.
class Student: def __init__(self, *args): if len(args) == 1: self.name = args[0] elif len(args) == 2: self.name = args[0] self.age = args[1] elif len(args) == 3: self.name = args[0] self.age = args[1] self.gender = args[2] st1 = Student("Shrey") print("Name:", st1.name) st2 = Student("Ram", 25) print(f"Name: {st2.name} and Age: {st2.age}") st3 = Student("Shyam", 26, "M") print(f"Name: {st3.name}, Age: {st3.age} and Gender: {st3.gender}")
When we run the above code, it will produce the following output −
Name: Shrey Name: Ram and Age: 25 Name: Shyam, Age: 26 and Gender: M