Ways to create constructors In Python - onlinetutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we’ll learn the concepts of constructors in Python. A constructor is a special method of a class in the Object-Oriented Programming which gets invoked automatically whenever an object of that class is created.
Constructors are primarily used to initialise the class data members to each object at the time of object instantiation. In Python, Constructors are declared using __init__() method which takes self as the first argument.
Default Constructor – This kind of constructor does not contain any parameter except self. Even if we do not declare any constructor in our class, a default constructor is automatically invoked but it is a good practice to involve a default constructor even if we do not require it.
Parametrised Constructor – This takes one or more arguments along with self to initialise a value to the class members to the objects.
Imagine we are a car collector and wants to keep a track of the cars information that we add in our collection and the count of the cars. It is not efficient to do all this manually. Let us implement this using class & constructor so that we can add the cars in our collection efficiently.
class Garage:
    make = None
    model = None
    color = None

    def __init__(self):
        pass

car1 = Garage()
car2= Garage()
car2.model = "x1"
print("Car 1 make: ",car1.make)
print("Car 1 model: ",car1.model)
print("Car 2 model: ",car2.model)
Output:
Car 1 make:  None
Car 1 model:  None
Car 2 model:  x1
We see that a default constructor will use default data member values for each object & we have to manually initialize the different values for class data members as we did for car2.model. Let’s use the parametrised constructor to avoid this.
class Garage:
    make = None
    model = None
    color = None

    def __init__(self,make,model,color):
        self.make=make
        self.model=model
        self.color=color

car1 = Garage("BMW","X1","Black")
car2= Garage("Honda","City","Silver")

print("Details of Car 1: \n",car1.__dict__)
print("Details of Car 2: \n",car2.__dict__)
Output:
Details of Car 1:
 {'make': 'BMW', 'model': 'X1', 'color': 'Black'}
Details of Car 2:
 {'make': 'Honda', 'model': 'City', 'color': 'Silver'}
Here, we have passed the class data members to the constructor so that whenever an object is created for this class with the appropriate number of arguments, then they will be automatically initialized. We have used __dict__ class attribute to output the information of the objects.
We can keep a track of the number of objects created by increment a data member inside the constructor. Note that the number of cars in a garage is a property of garage and does not depend upon each car, we will make a change in class member by using the name of the class rather than self keyword.
class Garage:
    make = None
    model = None
    color = None
    numCars = 0

    def __init__(self,make,model,color):
        self.make=make
        self.model=model
        self.color=color
        Garage.numCars = Garage.numCars+1

car1 = Garage("BMW","X1","Black")
car2= Garage("Honda","City","Silver")
car3 = Garage("Toyota","Fortuner","White")

print("Details of Car 1: \n",car1.__dict__)
print("Details of Car 2: \n",car2.__dict__)
print("Details of Car 3: \n",car3.__dict__)
print("Number of Cars in Garage: ",Garage.numCars)
Output:
Details of Car 1:
 {'make': 'BMW', 'model': 'X1', 'color': 'Black'}
Details of Car 2:
 {'make': 'Honda', 'model': 'City', 'color': 'Silver'}
Details of Car 3:
 {'make': 'Toyota', 'model': 'Fortuner', 'color': 'White'}
Number of Cars in Garage:  3

So we learn about what are constructors, types of constructors, and how to use them with example.
Python Oops
Happy Learning 🙂

How to remove empty lists from a Python List
Modes of Python Program
Python Tuple Data Structure in Depth
How to merge two lists in Python
How to read a text file in Python ?
What are the different ways to Sort Objects in Python ?
4 ways to create an Object in Java
2 ways to Create ArrayList in Java
Python – How to create Zip File in Python ?
How to Create or Delete Directories in Python ?
How to create Python Iterable class ?
What is Java Constructor and Types of Constructors
5 Ways to Iterate ArrayList in Java
C Program – Ways to Generate Fibonacci Series
Python – How to merge two dict in Python ?

How to remove empty lists from a Python List
Modes of Python Program
Python Tuple Data Structure in Depth
How to merge two lists in Python
How to read a text file in Python ?
What are the different ways to Sort Objects in Python ?
4 ways to create an Object in Java
2 ways to Create ArrayList in Java
Python – How to create Zip File in Python ?
How to Create or Delete Directories in Python ?
How to create Python Iterable class ?
What is Java Constructor and Types of Constructors
5 Ways to Iterate ArrayList in Java
C Program – Ways to Generate Fibonacci Series
Python – How to merge two dict in Python ?
 


Δ
 Python – Introduction
 Python – Features
 Python – Install on Windows
 Python – Modes of Program
 Python – Number System
 Python – Identifiers
 Python – Operators
 Python – Ternary Operator
 Python – Command Line Arguments
 Python – Keywords
 Python – Data Types
 Python – Upgrade Python PIP
 Python – Virtual Environment
 Pyhton – Type Casting
 Python – String to Int
 Python – Conditional Statements
 Python – if statement
 Python – *args and **kwargs
 Python – Date Formatting
 Python – Read input from keyboard
 Python – raw_input
 Python – List In Depth
 Python – List Comprehension
 Python – Set in Depth
 Python – Dictionary in Depth
 Python – Tuple in Depth
 Python – Stack Datastructure
 Python – Classes and Objects
 Python – Constructors
 Python – Object Introspection
 Python – Inheritance
 Python – Decorators
 Python – Serialization with Pickle
 Python – Exceptions Handling
 Python – User defined Exceptions
 Python – Multiprocessing
 Python – Default function parameters
 Python – Lambdas Functions
 Python – NumPy Library
 Python – MySQL Connector
 Python – MySQL Create Database
 Python – MySQL Read Data
 Python – MySQL Insert Data
 Python – MySQL Update Records
 Python – MySQL Delete Records
 Python – String Case Conversion
 Howto – Find biggest of 2 numbers
 Howto – Remove duplicates from List
 Howto – Convert any Number to Binary
 Howto  – Merge two Lists
 Howto – Merge two dicts
 Howto – Get Characters Count in a File
 Howto – Get Words Count in a File
 Howto – Remove Spaces from String
 Howto –  Read Env variables
 Howto – Read a text File
 Howto – Read a JSON File
 Howto –  Read Config.ini files
 Howto – Iterate Dictionary
 Howto – Convert List Of Objects to CSV
 Howto – Merge two dict in Python
 Howto – create Zip File
 Howto – Get OS info
 Howto – Get size of Directory
 Howto – Check whether a file exists
 Howto –  Remove key from dictionary
 Howto – Sort Objects
 Howto – Create or Delete Directories
 Howto – Read CSV File
 Howto – Create Python Iterable class
 Howto – Access for loop index
 Howto – Clear all elements from List
 Howto – Remove empty lists from a List
 Howto – Remove special characters from String
 Howto – Sort dictionary by key
 Howto – Filter a list