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.






Quick Enquiry

Please wait while submission in progress...


Contact Us

Chennai

  93450 45466

Bangalore

 93450 45466

Coimbatore

 95978 88270

Online

93450 45466

Madurai

97900 94102

Pondicherry

93635 21112

For Hiring

 93840 47472
 hr@fita.in

Corporate Training

 90036 23340


Read More Read less

FITA Academy Branches

Chennai

Bangalore

Coimbatore

Other Locations

FITA Academy - Velachery
Plot No 7, 2nd floor,
Vadivelan Nagar,
Velachery Main Road,
Velachery, Chennai - 600042
Tamil Nadu

    :   93450 45466

FITA Academy - Anna Nagar
No 14, Block No, 338, 2nd Ave,
Anna Nagar,
Chennai 600 040, Tamil Nadu
Next to Santhosh Super Market

    :   93450 45466

FITA Academy - T Nagar
05, 5th Floor, Challa Mall,
T Nagar,
Chennai 600 017, Tamil Nadu
Opposite to Pondy Bazaar Globus

    :   93450 45466

FITA Academy - Tambaram
Nehru Nagar, Kadaperi,
GST Road, West Tambaram,
Chennai 600 045, Tamil Nadu
Opposite to Saravana Jewellers Near MEPZ

    :   93450 45466

FITA Academy - Thoraipakkam
5/350, Old Mahabalipuram Road,
Okkiyam Thoraipakkam,
Chennai 600 097, Tamil Nadu
Next to Cognizant Thoraipakkam Office and Opposite to Nilgris Supermarket

    :   93450 45466

FITA Academy - Porur
17, Trunk Rd,
Porur
Chennai 600116, Tamil Nadu
Above Maharashtra Bank

    :   93450 45466

FITA Academy Marathahalli
No 7, J J Complex,
ITPB Road, Aswath Nagar,
Marathahalli Post,
Bengaluru 560037

    :   93450 45466

FITA Academy - Saravanampatty
First Floor, Promenade Tower,
171/2A, Sathy Road, Saravanampatty,
Coimbatore - 641035
Tamil Nadu

    :   95978 88270

FITA Academy - Singanallur
348/1, Kamaraj Road,
Varadharajapuram, Singanallur,
Coimbatore - 641015
Tamil Nadu

    :   95978 88270

FITA Academy - Madurai
No.2A, Sivanandha salai,
Arapalayam Cross Road,
Ponnagaram Colony,
Madurai - 625016, Tamil Nadu

    :   97900 94102

FITA Academy - Pondicherry
410, Villianur Main Rd,
Sithananda Nagar, Nellitope,
Puducherry - 605005
Near IG Square

    :   93635 21112

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

    Adyar, Adambakkam, Anna Salai, Ambattur, Ashok Nagar, Aminjikarai, Anna Nagar, Besant Nagar, Chromepet, Choolaimedu, Guindy, Egmore, K.K. Nagar, Kodambakkam, Koyambedu, Ekkattuthangal, Kilpauk, Meenambakkam, Medavakkam, Nandanam, Nungambakkam, Madipakkam, Teynampet, Nanganallur, Navalur, Mylapore, Pallavaram, Purasaiwakkam, OMR, Porur, Pallikaranai, Poonamallee, Perambur, Saidapet, Siruseri, St.Thomas Mount, Perungudi, T.Nagar, Sholinganallur, Triplicane, Thoraipakkam, Tambaram, Vadapalani, Valasaravakkam, Villivakkam, Thiruvanmiyur, West Mambalam, Velachery and Virugambakkam.

    FITA Velachery or T Nagar or Thoraipakkam OMR or Anna Nagar or Tambaram or Porur 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!