Can We Have Multiple Constructors In Python?

Krish Naik · Intermediate ·📐 ML Fundamentals ·3y ago

Key Takeaways

Explains if Python can have multiple constructors like other programming languages

Full Transcript

hello all my name is krishnak and welcome to my youtube channel so guys today in this video we are going to discuss about an interview question that was recently asked to one of my subscriber saying that can we have multiple constructors in python okay so what does this basically mean let's say that i'm i just want to create a simple class let's say my class name is animal okay and uh i've actually created it so here uh quickly you know i've made it very simple uh because of the github co-pilot and i'd actually written this code and uploaded it in the github anyhow it was able to extract it so over here what we have done is that i've defined two constructors one is init okay here i'm taking two parameters name and species okay and here i am defining self.name is equal to name so these are my class attributes these are my uh yeah class attributes names and species and this specific thing when we are initializing object we are basically applying our poor we are we are assigning that particular value over here right similarly what i have actually done and in other programming language you can definitely have multiple constructors based on the number of parameters that you define right so in this particular case i have again defined a constructor and here instead of just writing two things two two attributes uh two values that we will pass during initialization of the objects here we are passing three name species and age okay so here we have basically again created three uh variables so attributes i'll say not variables attributes so here you have name species and age okay and finally we create a function make sound something something okay dot name and sound we are just passing it now this is my uh animal class okay now i hope everybody has got this now what if you will be seeing that if i initialize if i initialize some something if i initialize something and see that how this will specifically look like i want to initialize an object of animal let's say uh this animal name is dog okay and i'm just going to initialize it and what are things i really want to call someone let's call this constructor okay this constructor so over here you'll be seeing that this constructor basically takes name and species so it is dog comma and here i am basically saying the species is mammal okay so here are my two information so what happens as soon as i probably initialize this automatically it will go to the init method and it will basically um you know assign this dog over here and species over here so dog will get assigned to the name and mammal will get assigned to the species and this is how it should basically work right uh so let's go ahead and quickly you know just run this code or over here you have so i'm just going to run python constructors dot py um it's okay i can remove this so here very much important something you can see over here as soon as i run this it is basically showing that type init missing one required positional argument age okay so here you can quickly see that age is basically given to the second constructor okay so from this you can definitely see that what happened is that as soon as i defined my second constructor this has overridden the first constructor okay now what if i do i go over here and probably write the age also let's say i'm going to write the age as 15 okay probably the dog is 15 years okay and let me just print print the dog age okay so if i write dog dot age uh you will be uh dog dot age which is a variable i'll be able to see this okay so i will go over here and again print let me clear the screen uh python constructor dot py so this will also work so here you can see now the dog age is printed as 15 okay so in python definitely you cannot create multiple constructors but there is a hack okay you can create a multi constructor but by using something called as positional argument okay but again here when you are creating your positional argument on the fly inside the init you can create your own attributes and you can use those those attributes in any kind of functions now let me show you how that can be done now what i am actually saying is that instead of writing multiple units now you understood what is the problem with respect to writing constructors in python this as you keep on writing this will get overrated right overridden basically means now suppose if i go ahead and probably write another definition of init and probably let's say i'm going to use just one parameter one more and here i'm just going to assign some value as 5 okay let's say i'm going to assign some value as 5 and here i'm just going to say that okay self dot number is equal to 5 okay i'm just doing this okay or instead of 5 let me just define any variable fine i'll just say number okay and this will basically get assigned to this number now as soon as i run this now this will not be working this entire init or the constructor has already overridden this thing now how do we fix this issue okay this issue i will try to show you and i'll try to show you a simple hack now what i'm actually going to do over here is that instead of writing just self right i'll write self and here i will say it as a rgs now what is args it is a positional argument okay now in this position arguments i will say if let's say if the length of a rgs is double equal to one okay then what i'm actually going to do if it if i'm just passing one argument over there i am just going to say that okay this probably can be the name right so here i am just saying self.name cell.name is equal to args of zero okay so args of args is what positional argument so when i am saying args of 0 automatically this specific attribute is getting created now let me write another condition else if if length of arguments is is equal to two that basically means i'm just passing two arguments as my positional arguments then i may create two attributes like name and species and similarly if i probably like l if length of argument is three i may probably create another three arguments or three attributes like name species and age right now this is perfect just by using one indeed method now can i work into this and can i show you some amazing results let's see okay so now here i'm actually giving three attributes dog mammal and age now see whether this will work or not okay so i will quickly save this and let's go ahead and execute this over here so i'm just going to write python dot constructor.p1 so here now you can see that dog age is getting printed okay so in short you will also be able to see dog dot um species okay species is an attribute you can also print dog dot name okay so all the things you can actually do now if i try to execute it so here you can see 15 mammal dog right so everything is basically getting displayed over here in an amazing way right now what have you done over here suppose if you just pass one argument then on the fly you'll just be able to create one so one attributes right but again this is not a good practice you should not keep on doing this because as you keep on growing this specific class uh you have to keep on increasing or writing your own condition and creating your attributes but yes this can be an interview question and similarly one interview question was asked to one of my subscriber and he answered it correctly by using this specific technique okay so i hope you have understood this uh so if i probably also try to crawl this spread make underscores count so let me just write like dog dot make underscore scout woof so the hoof is the sound that he is probably making it so again if i try to execute it here you can see the animal is dog and says woof okay so definitely you can try it out and uh yes this was it for my side i hope you like this particular video please make sure that you subscribe the channel i'll see you in the next video have a great day thank you and all bye

Original Description

Python playlist: https://www.youtube.com/watch?v=bPrmA1SEN2k&list=PLZoTAELRMXVNUL99R4bDlVYsncUNvwUBB Please join as a member in my channel to get additional benefits like materials in Data Science, live streaming for Members and many more https://www.youtube.com/channel/UCNU_lfiiWBdtULKOw6X0Dig/join Please do subscribe my other channel too https://www.youtube.com/channel/UCjWY5hREA6FFYrthD0rZNIw Connect with me here: Twitter: https://twitter.com/Krishnaik06 Instagram: https://www.instagram.com/krishnaik06
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Krish Naik · Krish Naik · 0 of 60

← Previous Next →
1 Natural Language Processing|Stemming
Natural Language Processing|Stemming
Krish Naik
2 Natural Language Processing|BagofWords
Natural Language Processing|BagofWords
Krish Naik
3 Gaussian distribution or Normal Distribution in statisctics
Gaussian distribution or Normal Distribution in statisctics
Krish Naik
4 Natural Language Processing|TF-IDF for Machine Learning| Text Prerocessing
Natural Language Processing|TF-IDF for Machine Learning| Text Prerocessing
Krish Naik
5 Log Normal Distribution in Statistics
Log Normal Distribution in Statistics
Krish Naik
6 Covariance in Statistics
Covariance in Statistics
Krish Naik
7 Confusion matrix, Precision, Recall| Data Science Interview questions
Confusion matrix, Precision, Recall| Data Science Interview questions
Krish Naik
8 Tutorial 44-Balanced vs Imbalanced Dataset and how to handle Imbalanced Dataset
Tutorial 44-Balanced vs Imbalanced Dataset and how to handle Imbalanced Dataset
Krish Naik
9 Implementing a Spam classifier in python| Natural Language Processing
Implementing a Spam classifier in python| Natural Language Processing
Krish Naik
10 Tutorial 11-Exploratory Data Analysis(EDA) of Titanic dataset
Tutorial 11-Exploratory Data Analysis(EDA) of Titanic dataset
Krish Naik
11 Face Recognition using open CV and VGG 16 Transfer Learning
Face Recognition using open CV and VGG 16 Transfer Learning
Krish Naik
12 Pedestrian Detection using OpenCV from Videos
Pedestrian Detection using OpenCV from Videos
Krish Naik
13 Face and Eye Detection from Videos using HAAR Cascade Classifier
Face and Eye Detection from Videos using HAAR Cascade Classifier
Krish Naik
14 Reading, Writing and Displaying images with Opencv| OpenCV Tutorial
Reading, Writing and Displaying images with Opencv| OpenCV Tutorial
Krish Naik
15 OpenCV Installation | OpenCV tutorial
OpenCV Installation | OpenCV tutorial
Krish Naik
16 Face and Eye Detection from Images using HAAR Cascade Classifier
Face and Eye Detection from Images using HAAR Cascade Classifier
Krish Naik
17 Car Detection using HAAR Cascade and Opencv from Videos.
Car Detection using HAAR Cascade and Opencv from Videos.
Krish Naik
18 Using OpenFace for Face recognition in Keras
Using OpenFace for Face recognition in Keras
Krish Naik
19 OpenPose Tutorial with Tensorflow
OpenPose Tutorial with Tensorflow
Krish Naik
20 Multiple Linear Regression using python and sklearn
Multiple Linear Regression using python and sklearn
Krish Naik
21 Dimensional Reduction| Principal Component Analysis
Dimensional Reduction| Principal Component Analysis
Krish Naik
22 Movie Recommender System using Python
Movie Recommender System using Python
Krish Naik
23 TPR,FPR,FNR,TNR, Confusion Matrix
TPR,FPR,FNR,TNR, Confusion Matrix
Krish Naik
24 Precision, Recall and F1-Score
Precision, Recall and F1-Score
Krish Naik
25 Artificial Neural Network for Customer's Exit Prediction from Bank
Artificial Neural Network for Customer's Exit Prediction from Bank
Krish Naik
26 GridSearchCV- Select the best hyperparameter for any Classification Model
GridSearchCV- Select the best hyperparameter for any Classification Model
Krish Naik
27 RandomizedSearchCV- Select the best hyperparameter for any Classification Model
RandomizedSearchCV- Select the best hyperparameter for any Classification Model
Krish Naik
28 K Nearest Neighbor classification with Intuition and practical solution
K Nearest Neighbor classification with Intuition and practical solution
Krish Naik
29 K Means Clustering Intuition
K Means Clustering Intuition
Krish Naik
30 Create custom Alexa Skill- Lambda function- Part2
Create custom Alexa Skill- Lambda function- Part2
Krish Naik
31 Hierarchical Clustering intuition
Hierarchical Clustering intuition
Krish Naik
32 Implement Transfer Learning with a generic Code Template
Implement Transfer Learning with a generic Code Template
Krish Naik
33 Gender Classifier and Age Estimator using Resnet Convolution Neural Network
Gender Classifier and Age Estimator using Resnet Convolution Neural Network
Krish Naik
34 Unlock Your Application With Your Face using OpenCV
Unlock Your Application With Your Face using OpenCV
Krish Naik
35 Draw rectangle from webcam and sketch process it on a live feed
Draw rectangle from webcam and sketch process it on a live feed
Krish Naik
36 Complete Life Cycle of a Data Science Project
Complete Life Cycle of a Data Science Project
Krish Naik
37 How we can apply Machine Learning in Finance
How we can apply Machine Learning in Finance
Krish Naik
38 Deep Learning in Medical Science
Deep Learning in Medical Science
Krish Naik
39 How to switch your career to Data Science.
How to switch your career to Data Science.
Krish Naik
40 Linear Regression Mathematical Intuition
Linear Regression Mathematical Intuition
Krish Naik
41 Handle Categorical features using Python
Handle Categorical features using Python
Krish Naik
42 Machine Learning Algorithm- Which one to choose for your Problem?
Machine Learning Algorithm- Which one to choose for your Problem?
Krish Naik
43 DBSCAN Clustering Easily Explained with Implementation
DBSCAN Clustering Easily Explained with Implementation
Krish Naik
44 Curse of Dimensionality Easily explained| Machine Learning
Curse of Dimensionality Easily explained| Machine Learning
Krish Naik
45 Feature Selection Techniques Easily Explained | Machine Learning
Feature Selection Techniques Easily Explained | Machine Learning
Krish Naik
46 Tutorial 29-R square and Adjusted R square Clearly Explained| Machine Learning
Tutorial 29-R square and Adjusted R square Clearly Explained| Machine Learning
Krish Naik
47 Cross Validation using sklearn and python | Machine Learning
Cross Validation using sklearn and python | Machine Learning
Krish Naik
48 Handling Missing Data Easily Explained| Machine Learning
Handling Missing Data Easily Explained| Machine Learning
Krish Naik
49 Deploy Machine Learning Model using Flask
Deploy Machine Learning Model using Flask
Krish Naik
50 Deployment of Deep Learning Model using Flask
Deployment of Deep Learning Model using Flask
Krish Naik
51 How to Visualize Multiple Linear Regression in python
How to Visualize Multiple Linear Regression in python
Krish Naik
52 K Nearest Neighbour Easily Explained with Implementation
K Nearest Neighbour Easily Explained with Implementation
Krish Naik
53 Predicting Heart Disease using Machine Learning
Predicting Heart Disease using Machine Learning
Krish Naik
54 Predicting Lungs Disease using Deep Learning
Predicting Lungs Disease using Deep Learning
Krish Naik
55 Stock Sentiment Analysis using News Headlines
Stock Sentiment Analysis using News Headlines
Krish Naik
56 Random Forest(Bootstrap Aggregation) Easily Explained
Random Forest(Bootstrap Aggregation) Easily Explained
Krish Naik
57 Voting Classifier(Hard Voting and Soft Voting Classifier)
Voting Classifier(Hard Voting and Soft Voting Classifier)
Krish Naik
58 Credit Card Fraud Detection using Machine Learning from Kaggle
Credit Card Fraud Detection using Machine Learning from Kaggle
Krish Naik
59 Hyperparameter Optimization for Xgboost
Hyperparameter Optimization for Xgboost
Krish Naik
60 Tutorial 45-Handling imbalanced Dataset  using python- Part 1
Tutorial 45-Handling imbalanced Dataset using python- Part 1
Krish Naik

Related Reads

Up next
Dropout in Deep Learning
AnuTech-CH
Watch →