For Enquiry: 93450 45466

A Comprehensive Guide to Python Class Inheritance


Python classes consist of attributes and methods, where an attribute functions as a data storage variable. On the other hand, a class method is a function that is associated with a specific class and typically executes certain operations involving the class’s attributes. This article will explore the concept of class inheritance, parent and child classes, the advantages of inheritance, and provide Python examples to illustrate the concept.

If you have a comprehensive understanding of Python Inheritance, you can join Python Training in Chennai, which will help you have a better understanding of python class inheritance, types of inheritance, benefits of inheritance, how to create child classes, python inheritance basic concepts and techniques.

What is Class Inheritance?

In Python, the type of inheritance in python allows the creation of a new class that can utilize the methods and attributes of an already-defined class. The parent class, which possesses the methods and attributes to be inherited, can also be referred to as the base class or superclass. On the other hand, the child class, also known as the subclass, gains access to the parent class’s attributes and methods. Furthermore, it is possible to define a child class that inherits from multiple parent classes.

How to Create Child Classes?

A parent class contains methods and attributes that are inherited by a child class. Child classes have the ability to either override or customize the methods and attributes inherited from the parent class. Defining a parent class in Python is similar to defining a regular class, by creating a class with its own set of methods and attributes.

Here is an example illustrating a basic parent class. It includes an `__init__` method, similar to a standard class. Within the `__init__` method, a class attribute is defined and assigned a value. Additionally, a class method called `print_attribute` is implemented to display the attribute defined in the `__init__` method.


Class ParentClass:

def __init__(self, attribute):

self.attribute = attribute

def print_attribute(self):

print(Self.attribute)

How to Create Parent Classes?

A parent class contains methods and attributes that are inherited by a child class. Child classes have the ability to either override or customize the methods and attributes inherited from the parent class. Defining a parent class in Python is similar to defining a regular class, where you define a class with its own set of methods and attributes.

Here is an example illustrating a basic parent class. It includes an `__init__` method, similar to a standard class. Within the `__init__` method, a class attribute is defined and assigned a value. Additionally, a class method called `print_attribute` is implemented to display the attribute defined in the `__init__` method.


Class ParentClass:

def __init__(self, attribute):

self.attribute = attribute

def print_attribute(self):

print(Self.attribute)

Join FITA Academyโ€™s Python Training in Bangalore and start your journey in becoming a developer.

Benefits of Inheritance

Inheritance offers significant advantages by reducing code duplication in software development. It allows developers to create a hierarchy of classes that avoids repetitive code segments performing the same tasks. This not only enhances code readability but also greatly improves maintainability. For instance, if there are multiple instances in the code where the error rate of model predictions is calculated, it can be refactored into a method in the parent class, which can be inherited by child classes.

Well-designed hierarchical class structures using a type of inheritance in Python also simplify testing and debugging processes. Tasks are well-defined and concentrated in specific sections of the codebase. Therefore, when modifications need to be made to a particular task, locating the relevant code that requires modification becomes more straightforward. Furthermore, any changes made to a method in the parent class are automatically propagated to all the associated child classes.

Example of Class Inheritance in Python

Popular machine learning packages like Scikit-learn and Keras incorporate class inheritance, where child classes inherit from a parent class. For instance, classes such as linear regression, support vector machines, and random forests are child classes that inherit from the parent class BaseEstimator. The BaseEstimator class includes familiar methods like predict and fit, which are commonly used by data scientists.

An intriguing application involves creating custom child classes that inherit from parent classes using various packages. One can develop a custom dataframe class by inheriting from the DataFrame class in Pandas. Similarly, it is possible to define a custom classification class inheriting from the parent class RandomForestClassifier.

Custom parent and child classes can also be defined. For instance, one can establish a parent class specifying a specific type of classification model, with a child class analyzing the model’s output. Additionally, parent and child classes can be designed for visualizing model prediction data. The parent class can define attributes related to the classification model, inputs, and outputs, while the child class can generate visualizations like confusion matrices to evaluate the model’s performance.

In the context of classification models, the fictitious Telco churn dataset from Kaggle, freely available under the Apache 2.0 License, will be utilized. This dataset can be used, modified, and shared without restrictions.

Enrol for Machine Learning Training in Bangalore and start your career in AI/ML

Extending An Existing Class In A Python Package

Our churn data will first be read into a Pandas data frame:


import pandas as pd

df = pd.read_csv('telco_churn.csv')

Let’s define input and output next. In order to forecast churn, we will make use of the parameters MonthlyCharges, Gender, Tenure, InternetService, and OnlineSecurity. Let’s transform the category columns into values that computers can understand:


df['gender'] = df['gender'].astype('category')

df['gender_cat'] = df['gender'].cat.codes

df['InternetService'] = df['InternetService'].astype('category')

df['InternetService_cat'] = df['InternetService'].cat.codes

df['OnlineSecurity'] = df['OnlineSecurity'].astype('category')

df['OnlineSecurity_cat'] = df['OnlineSecurity'].cat.codes

df['Churn'] = np.where(df['Churn']=='Yes', 1, 0)

cols = ['MonthlyCharges', 'tenure', 'gender_cat', 'InternetService_cat', 'OnlineSecurity_cat']

Let's define input and output next:

from sklearn.model_selection import train_test_split

X = df[cols]

y = df['Churn']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

We can now provide our unique child class. Let’s define an empty class called CustomClassifier and import the Scikit-Learn random forest classifier. The RandomForestClassifier class will be accepted as an argument by the CustomClassifier:


from sklearn.ensemble import RandomForestClassifier

class CustomClassifier(RandomForestClassifier):

pass

In order to control the amount of our training and testing samples, we will define a test_size in our init method. The random forest class’s methods and attributes will be passed down to our custom class via the super method. Any new custom methods will extend the parent random forest class in this way.


from sklearn.ensemble import RandomForestClassifier

class CustomClassifier(RandomForestClassifier):

def __init__(self, test_size=0.2, **kwargs):

super().__init__(**kwargs)

self.test_size = test_size

We will now specify a method for dividing our data into training and testing:


from sklearn.ensemble import RandomForestClassifier

from sklearn.model_selection import train_test_split

class CustomClassifier(RandomForestClassifier):

def __init__(self, test_size=0.2, **kwargs):

super().__init__(**kwargs)

self.test_size = test_size

 

def split_data(self):

self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(X, y, test_size=self.custom_param, random_state=42)

The next step is to define a class instance. We will enter 0.2 as our test_size value. This implies that 20% of the data will be used for testing, while the remaining 80% will be used for training:


rf_model = CustomClassifier(0.2)

rf_model.split_data()

By publishing our child class's characteristics and methods, we can better comprehend it:

print(dir(rf_model))

We shall observe that all of the parent random forest object’s methods and properties are accessible to us through our child class:


['__abstractmethods__', '__annotations__', '__class__',

'__delattr__', '__dict__', '__dir__', '__doc__', '__eq__',

'__format__', '__ge__', '__getattribute__', '__getitem__',

'__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__',

'__iter__', '__le__', '__len__', '__lt__', '__module__', '__ne__',

'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',

'__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__',

'_abc_impl', '_check_feature_names', '_check_n_features',

'_compute_oob_predictions', '_estimator_type', '_get_oob_predictions',

'_get_param_names', '_get_tags', '_make_estimator', '_more_tags',

'_repr_html_', '_repr_html_inner', '_repr_mimebundle_',

'_required_parameters', '_set_oob_score_and_attributes',

'_validate_X_predict', '_validate_data', '_validate_estimator',

'_validate_y_class_weight', 'apply', 'base_estimator', 'bootstrap',

'ccp_alpha', 'class_weight', 'criterion', 'decision_path',

'estimator_params', 'feature_importances_', 'fit', 'get_params',

'max_depth', 'max_features', 'max_leaf_nodes', 'max_samples',

'min_impurity_decrease', 'min_samples_leaf', 'min_samples_split',

'min_weight_fraction_leaf', 'n_estimators', 'n_features_', 'n_jobs',

'oob_score', 'predict', 'predict_log_proba', 'predict_proba',

'random_state', 'score', 'set_params', 'split_data', 'test_size',

'verbose', 'warm_start']

Try fitting a random forest model to our training data using our custom class instance to demonstrate that it has access to the parent random forest class methods and attributes:


rf_model = CustomClassifier(0.2)

rf_model.split_data()

rf_model.fit(rf_model.X_train, rf_model.y_train)

Despite calling a function that is a part of the external class, this code runs without any errors. This is the splendour of the inheritance concept in python system! It enables you to quickly increase the functionality of already-existing classes, whether they are created specifically for a package or not.

In addition to methods, we have access to the class properties of the random forest classifier. The random forest classifier, for instance, has an attribute called feature significance. Let’s use our class instance to obtain and display the importance of a random forest feature:


importances = dict(zip(rf_model.feature_names_in_,ย 

rf_model.feature_importances_))

print("Feature Importances: ", importances)ย 

The outcomes are as follows:


Feature Importances: {'MonthlyCharges': 0.5192056776242303,

'tenure': 0.3435083140171441,

'gender_cat': 0.015069195786109523,

'InternetService_cat': 0.0457071535620191,

'OnlineSecurity_cat': 0.07650965901049701}

If you want to know more about the latest salary trends for Python Developer, Check out Python Developer Salary For Freshers, which will help you get an insight into the packages as per the companies, skills and experience.

Extending A Custom Parent Class

Python inheritance can be employed to extend the functionality of a custom parent class with a child class in various machine-learning scenarios. For instance, we can define a parent class responsible for training a random forest model and subsequently create a child class that utilises inherited attributes to generate a confusion matrix.

To begin, let’s define the class that will be utilised to construct our model. In this example, we will leverage the Seaborn library and the confusion metric method from the metrics module. Additionally, we will store the training and test sets as attributes within our parent class.


from sklearn.metrics import confusion_matrix

import seaborn as sns

class Model:

def __init__(self):

self.n_estimators = 10

self.max_depth = 10

self.y_test = y_test

self.y_train = y_train

self.X_train = X_train

self.X_test = X_test

The next step is to create a fit technique for fitting a random forest classifier to our training set of data:


from sklearn.metrics import confusion_matrix

import seaborn as sns

class Model:

...

def fit(self):

self.model = RandomForestClassifier(n_estimators = self.n_estimators, max_depth = self.max_depth, random_state=42)

self.model.fit(self.X_train, self.y_train)

Finally, a predict technique that outputs model predictions can be defined:


from sklearn.metrics import confusion_matrix

import seaborn as sns

class Model:

...

def predict(self):

self.y_pred = self.model.predict(X_test)

return self.y_pred

We can now specify our child class. Give our kid class the name “ModelVisulaization”. Our Model class’s method and attributes will be inherited by this one:


class ModelVisualization(Model):

def __init__(self):

super().__init__()

We will add a function that creates a confusion matrix to our model class as an extension:


class ModelVisualization(Model):

def __init__(self):

super().__init__()

def generate_confusion_matrix(self):

cm = confusion_matrix(self.y_test, self.y_pred)

cm = cm / cm.astype(np.float).sum(axis=1)

sns.heatmap(cm, annot=True, cmap='Blues')

Now that our kid class has been defined, we can plot our confusion matrix.


results = ModelVisualization()

results.fit()

results.predict()

results.generate_confusion_matrix()

The result is what follows:

Python class inheritance proves to be highly advantageous in the realm of data science and machine learning. It is frequently employed to enhance the functionality of classes present in existing machine learning packages. While we focused on extending the capabilities of the random forest classifier class, the same principles can be applied to expand the functionality of other classes like Pandas dataframes or data transformation classes such as standard scaler and min-max scaler. Possessing a fundamental understanding of using the inheritance concept in python to extend pre-existing classes holds immense value for data scientists and machine learning engineers.

Moreover, there are scenarios where multiple distinct tasks within different workflows necessitate customization. We explored an example of extending a custom class utilized for building a classification model by incorporating visualization capabilities. This approach enables the child class to inherit the methods and attributes from the modeling class while facilitating the generation of visualizations.

Now that you have understood the concepts of python class inheritance, types of inheritance, how to work with class inheritance and parent inheritance,python class inheritance, python class inheritance basic concepts and techniques. So, if you want to become a Python Developer, you can join a Python Training in Marathahalli and learn Internationalization, Localization, Localizing UI and form inputs and Time zones.





  • Trending Courses

    JAVA Training In Chennai Software Testing Training In Chennai Selenium Training In Chennai Python Training in Chennai Data Science Course In Chennai Digital Marketing Course In Chennai DevOps Training In Chennai German Classes In Chennai Artificial Intelligence Course in Chennai AWS Training in Chennai UI UX Design course in Chennai Tally course in Chennai Full Stack Developer course in Chennai Salesforce Training in Chennai ReactJS Training in Chennai CCNA course in Chennai Ethical Hacking course in Chennai RPA Training In Chennai Cyber Security Course in Chennai IELTS Coaching in Chennai Graphic Design Courses in Chennai Spoken English Classes in Chennai Data Analytics Course in Chennai

    Spring Training in Chennai Struts Training in Chennai Web Designing Course In Chennai Android Training In Chennai AngularJS Training in Chennai Dot Net Training In Chennai C / C++ Training In Chennai Django Training in Chennai PHP Training In Chennai iOS Training In Chennai SEO Training In Chennai Oracle Training In Chennai Cloud Computing Training In Chennai Big Data Hadoop Training In Chennai UNIX Training In Chennai Core Java Training in Chennai Placement Training In Chennai Javascript Training in Chennai Hibernate Training in Chennai HTML5 Training in Chennai Photoshop Classes in Chennai Mobile Testing Training in Chennai QTP Training in Chennai LoadRunner Training in Chennai Drupal Training in Chennai Manual Testing Training in Chennai WordPress Training in Chennai SAS Training in Chennai Clinical SAS Training in Chennai Blue Prism Training in Chennai Machine Learning course in Chennai Microsoft Azure Training in Chennai Selenium with Python Training in Chennai UiPath Training in Chennai Microsoft Dynamics CRM Training in Chennai VMware Training in Chennai R Training in Chennai Automation Anywhere Training in Chennai GST Training in Chennai Spanish Classes in Chennai Japanese Classes in Chennai TOEFL Coaching in Chennai French Classes in Chennai Informatica Training in Chennai Informatica MDM Training in Chennai Big Data Analytics courses in Chennai Hadoop Admin Training in Chennai Blockchain Training in Chennai Ionic Training in Chennai IoT Training in Chennai Xamarin Training In Chennai Node JS Training In Chennai Content Writing Course in Chennai Advanced Excel Training In Chennai Corporate Training in Chennai Embedded Training In Chennai Linux Training In Chennai Oracle DBA Training In Chennai PEGA Training In Chennai Primavera Training In Chennai Tableau Training In Chennai Spark Training In Chennai Appium Training In Chennai Soft Skills Training In Chennai JMeter Training In Chennai Power BI Training In Chennai Social Media Marketing Courses In Chennai Talend Training in Chennai HR Courses in Chennai Google Cloud Training in Chennai SQL Training In Chennai CCNP Training in Chennai PMP Training in Chennai OET Coaching Centre in Chennai Business Analytics Course in Chennai NextJS Course in Chennai Vue JS Course in Chennai Generative AI Course in Chennai

  • Read More Read less
  • Are You Located in Any of these Areas

    Adambakkam, Adyar, Akkarai, Alandur, Alapakkam, Alwarpet, Alwarthirunagar, Ambattur, Ambattur Industrial Estate, Aminjikarai, Anakaputhur, Anna Nagar, Anna Salai, Arumbakkam, Ashok Nagar, Avadi, Ayanavaram, Besant Nagar, Bharathi Nagar, Camp Road, Cenotaph Road, Central, Chetpet, Chintadripet, Chitlapakkam, Chengalpattu, Choolaimedu, Chromepet, CIT Nagar, ECR, Eechankaranai, Egattur, Egmore, Ekkatuthangal, Gerugambakkam, Gopalapuram, Guduvanchery, Guindy, Injambakkam, Irumbuliyur, Iyyappanthangal, Jafferkhanpet, Jalladianpet, Kanathur, Kanchipuram, Kandhanchavadi, Kandigai, Karapakkam, Kasturbai Nagar, Kattankulathur, Kattupakkam, Kazhipattur, Keelkattalai, Kelambakkam, Kilpauk, KK Nagar, Kodambakkam, Kolapakkam, Kolathur, Kottivakkam, Kotturpuram, Kovalam, Kovilambakkam, Kovilanchery, Koyambedu, Kumananchavadi, Kundrathur, Little Mount, Madambakkam, Madhavaram, Madipakkam, Maduravoyal, Mahabalipuram, Mambakkam, Manapakkam, Mandaveli, Mangadu, Mannivakkam, Maraimalai Nagar, Medavakkam, Meenambakkam, Mogappair, Moolakadai, Moulivakkam, Mount Road, MRC Nagar, Mudichur, Mugalivakkam, Muttukadu, Mylapore, Nandambakkam, Nandanam, Nanganallur, Nanmangalam, Narayanapuram, Navalur, Neelankarai, Nesapakkam, Nolambur, Nungambakkam, OMR, Oragadam, Ottiyambakkam, Padappai, Padi, Padur, Palavakkam, Pallavan Salai, Pallavaram, Pallikaranai, Pammal, Parangimalai, Paruthipattu, Pazhavanthangal, Perambur, Perumbakkam, Perungudi, Polichalur, Pondy Bazaar, Ponmar, Poonamallee, Porur, Pudupakkam, Pudupet, Purasaiwakkam, Puzhuthivakkam, RA Puram, Rajakilpakkam, Ramapuram, Red Hills, Royapettah, Saidapet, Saidapet East, Saligramam, Sanatorium, Santhome, Santhosapuram, Selaiyur, Sembakkam, Semmanjeri, Shenoy Nagar, Sholinganallur, Singaperumal Koil, Siruseri, Sithalapakkam, Srinivasa Nagar, St Thomas Mount, T Nagar, Tambaram, Tambaram East, Taramani, Teynampet, Thalambur, Thirumangalam, Thirumazhisai, Thiruneermalai, Thiruvallur, Thiruvanmiyur, Thiruverkadu, Thiruvottiyur, Thoraipakkam, Thousand Light, Tidel Park, Tiruvallur, Triplicane, TTK Road, Ullagaram, Urapakkam, Uthandi, Vadapalani, Vadapalani East, Valasaravakkam, Vallalar Nagar, Valluvar Kottam, Vanagaram, Vandalur, Vasanta Nagar, Velachery, Vengaivasal, Vepery, Vettuvankeni, Vijaya Nagar, Villivakkam, Virugambakkam, West Mambalam, West Saidapet

    FITA Velachery or T Nagar or Thoraipakkam OMR or Anna Nagar or Tambaram or Porur or Pallikaranai branch is just few kilometre away from your location. If you need the best training in Chennai, driving a couple of extra kilometres is worth it!