How to use class method as an alternate constructor in OOPs in python

This recipe helps you use class method as an alternate constructor in OOPs in python

Recipe Objective

This recipe explains how to use the class method as an alternate constructor.

Alternate Constructor

In python, we can define class methods using the @classmethod decorator and a special first argument cls. Class methods are generally used to define methods that returns an instance of the class In the below program we have created a Student class to call the constructor that creates Student object given the value of name, age, and roll but you also want to be able to create Students objects from strings like Max-19-22.

class Student:
    def __init__(self, name, age, roll):
        self.name = name
        self.age = age
        self.roll = roll
    
    @classmethod
    def AlternateConstructor(cls, student_string):
        student_string = student_string.split("-")
        return cls(student_string[0], int(student_string[1]), int(student_string[2]))

Sam = Student("Sam", 18, 32)
Max = Student.AlternateConstructor("Max-19-22")

print(Sam.__dict__)
print(Max.__dict__)

 

What Users are saying..

profile image

Gautam Vermani

Data Consultant at Confidential
linkedin profile url

Having worked in the field of Data Science, I wanted to explore how I can implement projects in other domains, So I thought of connecting with ProjectPro. A project that helped me absorb this topic... Read More

Relevant Projects

BERT Text Classification using DistilBERT and ALBERT Models
This Project Explains how to perform Text Classification using ALBERT and DistilBERT

Multi-Class Text Classification with Deep Learning using BERT
In this deep learning project, you will implement one of the most popular state of the art Transformer models, BERT for Multi-Class Text Classification

Build CI/CD Pipeline for Machine Learning Projects using Jenkins
In this project, you will learn how to create a CI/CD pipeline for a search engine application using Jenkins.

Ola Bike Rides Request Demand Forecast
Given big data at taxi service (ride-hailing) i.e. OLA, you will learn multi-step time series forecasting and clustering with Mini-Batch K-means Algorithm on geospatial data to predict future ride requests for a particular region at a given time.

Build a Graph Based Recommendation System in Python-Part 2
In this Graph Based Recommender System Project, you will build a recommender system project for eCommerce platforms and learn to use FAISS for efficient similarity search.

Azure Deep Learning-Deploy RNN CNN models for TimeSeries
In this Azure MLOps Project, you will learn to perform docker-based deployment of RNN and CNN Models for Time Series Forecasting on Azure Cloud.

Learn to Build a Neural network from Scratch using NumPy
In this deep learning project, you will learn to build a neural network from scratch using NumPy

Build a Customer Churn Prediction Model using Decision Trees
Develop a customer churn prediction model using decision tree machine learning algorithms and data science on streaming service data.

Learn to Build a Polynomial Regression Model from Scratch
In this Machine Learning Regression project, you will learn to build a polynomial regression model to predict points scored by the sports team.

Learn Hyperparameter Tuning for Neural Networks with PyTorch
In this Deep Learning Project, you will learn how to optimally tune the hyperparameters (learning rate, epochs, dropout, early stopping) of a neural network model in PyTorch to improve model performance.