{"id":94189,"date":"2023-08-21T05:41:05","date_gmt":"2023-08-21T05:41:05","guid":{"rendered":"https:\/\/www.fita.in\/?p=94189"},"modified":"2023-10-09T06:36:22","modified_gmt":"2023-10-09T06:36:22","slug":"a-comprehensive-guide-to-python-class-inheritance","status":"publish","type":"post","link":"https:\/\/www.fita.in\/a-comprehensive-guide-to-python-class-inheritance\/","title":{"rendered":"A Comprehensive Guide to Python Class Inheritance"},"content":{"rendered":"
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.<\/p>\r\n
If you have a comprehensive understanding of Python Inheritance, you can join Python Training in Chennai<\/a>, 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.<\/p>\r\n\r\n 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.<\/p>\r\n 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.<\/p>\r\n 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.<\/p>\r\n\r\n 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.<\/p>\r\n 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.<\/p>\r\n\r\n Join FITA Academy<\/a>\u2019s Python Training in Bangalore<\/a> and start your journey in becoming a developer.<\/p>\r\n\r\n 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.<\/p>\r\n 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.<\/p>\r\n\r\n 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.<\/p>\r\n 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.<\/p>\r\n 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.<\/p>\r\n 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.<\/p>\r\n Enrol for Machine Learning Training in Bangalore<\/a> and start your career in AI\/ML<\/p>\r\n\r\n Our churn data will first be read into a Pandas data frame:<\/p>\r\n\r\n 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:<\/p>\r\n\r\n 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:<\/p>\r\n\r\n 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.<\/p>\r\n\r\n We will now specify a method for dividing our data into training and testing:<\/p>\r\n\r\n 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:<\/p>\r\n\r\n We shall observe that all of the parent random forest object’s methods and properties are accessible to us through our child class:<\/p>\r\n\r\n 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:<\/p>\r\n\r\n 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.<\/p>\r\n 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:<\/p>\r\n\r\n The outcomes are as follows:<\/p>\r\n\r\n If you want to know more about the latest salary trends for Python Developer, Check out Python Developer Salary For Freshers<\/a>, which will help you get an insight into the packages as per the companies, skills and experience.<\/p>\r\n\r\n 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.<\/p>\r\n 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.<\/p>\r\n\r\n The next step is to create a fit technique for fitting a random forest classifier to our training set of data:<\/p>\r\n\r\n Finally, a predict technique that outputs model predictions can be defined:<\/p>\r\n\r\n 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:<\/p>\r\n\r\n We will add a function that creates a confusion matrix to our model class as an extension:<\/p>\r\n\r\n Now that our kid class has been defined, we can plot our confusion matrix.<\/p>\r\n\r\n The result is what follows:<\/p>\r\nWhat is Class Inheritance?<\/strong><\/h2>\r\n
\r\nHow to Create Child Classes?<\/strong><\/h2>\r\n
\r\nClass ParentClass:\r\n\r\ndef __init__(self, attribute):\r\n\r\nself.attribute = attribute\r\n\r\ndef print_attribute(self):\r\n\r\nprint(Self.attribute)\r\n<\/code><\/pre>\r\n<\/div>\r\nHow to Create Parent Classes?<\/strong><\/h2>\r\n
\r\nClass ParentClass:\r\n\r\ndef __init__(self, attribute):\r\n\r\nself.attribute = attribute\r\n\r\ndef print_attribute(self):\r\n\r\nprint(Self.attribute)\r\n<\/code><\/pre>\r\n<\/div>\r\nBenefits of Inheritance<\/strong><\/h2>\r\n
Example of Class Inheritance in Python<\/strong><\/h2>\r\n
Extending An Existing Class In A Python Package<\/strong><\/h2>\r\n
\r\nimport pandas as pd\r\n\r\ndf = pd.read_csv('telco_churn.csv')\r\n<\/code><\/pre>\r\n<\/div>\r\n\r\ndf['gender'] = df['gender'].astype('category')\r\n\r\ndf['gender_cat'] = df['gender'].cat.codes\r\n\r\ndf['InternetService'] = df['InternetService'].astype('category')\r\n\r\ndf['InternetService_cat'] = df['InternetService'].cat.codes\r\n\r\ndf['OnlineSecurity'] = df['OnlineSecurity'].astype('category')\r\n\r\ndf['OnlineSecurity_cat'] = df['OnlineSecurity'].cat.codes\r\n\r\ndf['Churn'] = np.where(df['Churn']=='Yes', 1, 0)\r\n\r\ncols = ['MonthlyCharges', 'tenure', 'gender_cat', 'InternetService_cat', 'OnlineSecurity_cat']\r\n\r\nLet's define input and output next:\r\n\r\nfrom sklearn.model_selection import train_test_split\r\n\r\nX = df[cols]\r\n\r\ny = df['Churn']\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\r\n<\/code><\/pre>\r\n<\/div>\r\n\r\nfrom sklearn.ensemble import RandomForestClassifier\r\n\r\nclass CustomClassifier(RandomForestClassifier):\r\n\r\npass\r\n<\/code><\/pre>\r\n<\/div>\r\n\r\nfrom sklearn.ensemble import RandomForestClassifier\r\n\r\nclass CustomClassifier(RandomForestClassifier):\r\n\r\ndef __init__(self, test_size=0.2, **kwargs):\r\n\r\nsuper().__init__(**kwargs)\r\n\r\nself.test_size = test_size\r\n<\/code><\/pre>\r\n<\/div>\r\n\r\nfrom sklearn.ensemble import RandomForestClassifier\r\n\r\nfrom sklearn.model_selection import train_test_split\r\n\r\nclass CustomClassifier(RandomForestClassifier):\r\n\r\ndef __init__(self, test_size=0.2, **kwargs):\r\n\r\nsuper().__init__(**kwargs)\r\n\r\nself.test_size = test_size\r\n\r\n \r\n\r\ndef split_data(self):\r\n\r\nself.X_train, self.X_test, self.y_train, self.y_test = train_test_split(X, y, test_size=self.custom_param, random_state=42)\r\n<\/code><\/pre>\r\n<\/div>\r\n\r\nrf_model = CustomClassifier(0.2)\r\n\r\nrf_model.split_data()\r\n\r\nBy publishing our child class's characteristics and methods, we can better comprehend it:\r\n\r\nprint(dir(rf_model))\r\n<\/code><\/pre>\r\n<\/div>\r\n\r\n['__abstractmethods__', '__annotations__', '__class__',\r\n\r\n'__delattr__', '__dict__', '__dir__', '__doc__', '__eq__',\r\n\r\n'__format__', '__ge__', '__getattribute__', '__getitem__',\r\n\r\n'__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__',\r\n\r\n'__iter__', '__le__', '__len__', '__lt__', '__module__', '__ne__',\r\n\r\n'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',\r\n\r\n'__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__',\r\n\r\n'_abc_impl', '_check_feature_names', '_check_n_features',\r\n\r\n'_compute_oob_predictions', '_estimator_type', '_get_oob_predictions',\r\n\r\n'_get_param_names', '_get_tags', '_make_estimator', '_more_tags',\r\n\r\n'_repr_html_', '_repr_html_inner', '_repr_mimebundle_',\r\n\r\n'_required_parameters', '_set_oob_score_and_attributes',\r\n\r\n'_validate_X_predict', '_validate_data', '_validate_estimator',\r\n\r\n'_validate_y_class_weight', 'apply', 'base_estimator', 'bootstrap',\r\n\r\n'ccp_alpha', 'class_weight', 'criterion', 'decision_path',\r\n\r\n'estimator_params', 'feature_importances_', 'fit', 'get_params',\r\n\r\n'max_depth', 'max_features', 'max_leaf_nodes', 'max_samples',\r\n\r\n'min_impurity_decrease', 'min_samples_leaf', 'min_samples_split',\r\n\r\n'min_weight_fraction_leaf', 'n_estimators', 'n_features_', 'n_jobs',\r\n\r\n'oob_score', 'predict', 'predict_log_proba', 'predict_proba',\r\n\r\n'random_state', 'score', 'set_params', 'split_data', 'test_size',\r\n\r\n'verbose', 'warm_start']\r\n<\/code><\/pre>\r\n<\/div>\r\n\r\nrf_model = CustomClassifier(0.2)\r\n\r\nrf_model.split_data()\r\n\r\nrf_model.fit(rf_model.X_train, rf_model.y_train)\r\n<\/code><\/pre>\r\n<\/div>\r\n\r\nimportances = dict(zip(rf_model.feature_names_in_,\u00a0\r\n\r\nrf_model.feature_importances_))\r\n\r\nprint(\"Feature Importances: \", importances)\u00a0\r\n<\/code><\/pre>\r\n<\/div>\r\n\r\nFeature Importances: {'MonthlyCharges': 0.5192056776242303,\r\n\r\n'tenure': 0.3435083140171441,\r\n\r\n'gender_cat': 0.015069195786109523,\r\n\r\n'InternetService_cat': 0.0457071535620191,\r\n\r\n'OnlineSecurity_cat': 0.07650965901049701}\r\n<\/code><\/pre>\r\n<\/div>\r\nExtending A Custom Parent Class<\/strong><\/h2>\r\n
\r\nfrom sklearn.metrics import confusion_matrix\r\n\r\nimport seaborn as sns\r\n\r\nclass Model:\r\n\r\ndef __init__(self):\r\n\r\nself.n_estimators = 10\r\n\r\nself.max_depth = 10\r\n\r\nself.y_test = y_test\r\n\r\nself.y_train = y_train\r\n\r\nself.X_train = X_train\r\n\r\nself.X_test = X_test\r\n<\/code><\/pre>\r\n<\/div>\r\n\r\nfrom sklearn.metrics import confusion_matrix\r\n\r\nimport seaborn as sns\r\n\r\nclass Model:\r\n\r\n...\r\n\r\ndef fit(self):\r\n\r\nself.model = RandomForestClassifier(n_estimators = self.n_estimators, max_depth = self.max_depth, random_state=42)\r\n\r\nself.model.fit(self.X_train, self.y_train)\r\n<\/code><\/pre>\r\n<\/div>\r\n\r\nfrom sklearn.metrics import confusion_matrix\r\n\r\nimport seaborn as sns\r\n\r\nclass Model:\r\n\r\n...\r\n\r\ndef predict(self):\r\n\r\nself.y_pred = self.model.predict(X_test)\r\n\r\nreturn self.y_pred\r\n<\/code><\/pre>\r\n<\/div>\r\n\r\nclass ModelVisualization(Model):\r\n\r\ndef __init__(self):\r\n\r\nsuper().__init__()\r\n<\/code><\/pre>\r\n<\/div>\r\n\r\nclass ModelVisualization(Model):\r\n\r\ndef __init__(self):\r\n\r\nsuper().__init__()\r\n\r\ndef generate_confusion_matrix(self):\r\n\r\ncm = confusion_matrix(self.y_test, self.y_pred)\r\n\r\ncm = cm \/ cm.astype(np.float).sum(axis=1)\r\n\r\nsns.heatmap(cm, annot=True, cmap='Blues')\r\n<\/code><\/pre>\r\n<\/div>\r\n\r\nresults = ModelVisualization()\r\n\r\nresults.fit()\r\n\r\nresults.predict()\r\n\r\nresults.generate_confusion_matrix()<\/code><\/pre>\r\n<\/div>\r\n
\r\n