{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [], "authorship_tag": "ABX9TyNwounPuVckaUDocFE56d+y", "include_colab_link": true }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "markdown", "metadata": { "id": "view-in-github", "colab_type": "text" }, "source": [ "\"Open" ] }, { "cell_type": "markdown", "source": [ "**Types Of Inheritance**\n", "In Python, based upon the number of child and parent classes involved, there are five types of inheritance. The type of inheritance are listed below:\n", "\n", "Single inheritance\n", "Multiple Inheritance\n", "Multilevel inheritance\n", "Hierarchical Inheritance\n", "Hybrid Inheritance" ], "metadata": { "id": "1FNNtqGYcXZG" } }, { "cell_type": "code", "execution_count": 1, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "FUFew0urb1Vn", "outputId": "340358da-de4f-46c8-9e62-ac79d76fa4f0" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Mammals can give direct birth.\n", "Winged animals can flap.\n", "Super Class method called\n", "Derived class 1 method called\n", "Derived class 2 method called\n", "Super Class 1 method called\n", "Inside Vehicle class\n", "Inside Car class\n", "Inside Person class\n", "Name: Jessa Age: 28\n", "Inside Company class\n", "Name: Google location: Atlanta\n", "Inside Employee class\n", "Salary: 12000 Skill: Machine Learning\n", "Inside Vehicle class\n", "Inside Car class\n", "Inside SportsCar class\n", "This is Vehicle\n", "Car name is: BMW\n", "This is Vehicle\n", "Truck name is: Ford\n", "Inside Vehicle class\n", "Inside Car class\n", "Inside SportsCar class\n", "Jessa works at Google\n", "True\n", "False\n", "False\n", "True\n", "True\n", "max speed is 200 Km/Hour\n" ] } ], "source": [ "class Mammal:\n", " def mammal_info(self):\n", " print(\"Mammals can give direct birth.\")\n", "\n", "class WingedAnimal:\n", " def winged_animal_info(self):\n", " print(\"Winged animals can flap.\")\n", "\n", "class Bat(Mammal, WingedAnimal):\n", " pass\n", "\n", "# create an object of Bat class\n", "b1 = Bat()\n", "\n", "b1.mammal_info()\n", "b1.winged_animal_info()\n", "\n", "class SuperClass:\n", "\n", " def super_method(self):\n", " print(\"Super Class method called\")\n", "\n", "# define class that derive from SuperClass\n", "class DerivedClass1(SuperClass):\n", " def derived1_method(self):\n", " print(\"Derived class 1 method called\")\n", "\n", "# define class that derive from DerivedClass1\n", "class DerivedClass2(DerivedClass1):\n", "\n", " def derived2_method(self):\n", " print(\"Derived class 2 method called\")\n", "\n", "# create an object of DerivedClass2\n", "d2 = DerivedClass2()\n", "\n", "d2.super_method() # Output: \"Super Class method called\"\n", "\n", "d2.derived1_method() # Output: \"Derived class 1 method called\"\n", "\n", "d2.derived2_method() # Output: \"Derived class 2 method called\"\n", "\n", "class SuperClass1:\n", " def info(self):\n", " print(\"Super Class 1 method called\")\n", "\n", "class SuperClass2:\n", " def info(self):\n", " print(\"Super Class 2 method called\")\n", "\n", "class Derived(SuperClass1, SuperClass2):\n", " pass\n", "\n", "d1 = Derived()\n", "d1.info()\n", "\n", "# Output: \"Super Class 1 method called\"\n", "\n", "# Base class\n", "class Vehicle:\n", " def Vehicle_info(self):\n", " print('Inside Vehicle class')\n", "\n", "# Child class\n", "class Car(Vehicle):\n", " def car_info(self):\n", " print('Inside Car class')\n", "\n", "# Create object of Car\n", "car = Car()\n", "\n", "# access Vehicle's info using car object\n", "car.Vehicle_info()\n", "car.car_info()\n", "\n", "\n", "# Parent class 1\n", "class Person:\n", " def person_info(self, name, age):\n", " print('Inside Person class')\n", " print('Name:', name, 'Age:', age)\n", "\n", "# Parent class 2\n", "class Company:\n", " def company_info(self, company_name, location):\n", " print('Inside Company class')\n", " print('Name:', company_name, 'location:', location)\n", "\n", "# Child class\n", "class Employee(Person, Company):\n", " def Employee_info(self, salary, skill):\n", " print('Inside Employee class')\n", " print('Salary:', salary, 'Skill:', skill)\n", "\n", "# Create object of Employee\n", "emp = Employee()\n", "\n", "# access data\n", "emp.person_info('Jessa', 28)\n", "emp.company_info('Google', 'Atlanta')\n", "emp.Employee_info(12000, 'Machine Learning')\n", "\n", "\n", "# Base class\n", "class Vehicle:\n", " def Vehicle_info(self):\n", " print('Inside Vehicle class')\n", "\n", "# Child class\n", "class Car(Vehicle):\n", " def car_info(self):\n", " print('Inside Car class')\n", "\n", "# Child class\n", "class SportsCar(Car):\n", " def sports_car_info(self):\n", " print('Inside SportsCar class')\n", "\n", "# Create object of SportsCar\n", "s_car = SportsCar()\n", "\n", "# access Vehicle's and Car info using SportsCar object\n", "s_car.Vehicle_info()\n", "s_car.car_info()\n", "s_car.sports_car_info()\n", "\n", "\n", "class Vehicle:\n", " def info(self):\n", " print(\"This is Vehicle\")\n", "\n", "class Car(Vehicle):\n", " def car_info(self, name):\n", " print(\"Car name is:\", name)\n", "\n", "class Truck(Vehicle):\n", " def truck_info(self, name):\n", " print(\"Truck name is:\", name)\n", "\n", "obj1 = Car()\n", "obj1.info()\n", "obj1.car_info('BMW')\n", "\n", "obj2 = Truck()\n", "obj2.info()\n", "obj2.truck_info('Ford')\n", "\n", "class Vehicle:\n", " def vehicle_info(self):\n", " print(\"Inside Vehicle class\")\n", "\n", "class Car(Vehicle):\n", " def car_info(self):\n", " print(\"Inside Car class\")\n", "\n", "class Truck(Vehicle):\n", " def truck_info(self):\n", " print(\"Inside Truck class\")\n", "\n", "# Sports Car can inherits properties of Vehicle and Car\n", "class SportsCar(Car, Vehicle):\n", " def sports_car_info(self):\n", " print(\"Inside SportsCar class\")\n", "\n", "# create object\n", "s_car = SportsCar()\n", "\n", "s_car.vehicle_info()\n", "s_car.car_info()\n", "s_car.sports_car_info()\n", "\n", "class Company:\n", " def company_name(self):\n", " return 'Google'\n", "\n", "class Employee(Company):\n", " def info(self):\n", " # Calling the superclass method using super()function\n", " c_name = super().company_name()\n", " print(\"Jessa works at\", c_name)\n", "\n", "# Creating object of child class\n", "emp = Employee()\n", "emp.info()\n", "\n", "class Company:\n", " def fun1(self):\n", " print(\"Inside parent class\")\n", "\n", "class Employee(Company):\n", " def fun2(self):\n", " print(\"Inside child class.\")\n", "\n", "class Player:\n", " def fun3(self):\n", " print(\"Inside Player class.\")\n", "\n", "# Result True\n", "print(issubclass(Employee, Company))\n", "\n", "# Result False\n", "print(issubclass(Employee, list))\n", "\n", "# Result False\n", "print(issubclass(Player, Company))\n", "\n", "# Result True\n", "print(issubclass(Employee, (list, Company)))\n", "\n", "# Result True\n", "print(issubclass(Company, (list, Company)))\n", "\n", "\n", "class Vehicle:\n", " def max_speed(self):\n", " print(\"max speed is 100 Km/Hour\")\n", "\n", "class Car(Vehicle):\n", " # overridden the implementation of Vehicle class\n", " def max_speed(self):\n", " print(\"max speed is 200 Km/Hour\")\n", "\n", "# Creating object of Car class\n", "car = Car()\n", "car.max_speed()\n" ] }, { "cell_type": "markdown", "source": [ "# **Hierarchical Inheritance**\n", "In Hierarchical inheritance, more than one child class is derived from a single parent class. In other words, we can say one parent class and multiple child classes." ], "metadata": { "id": "wg34H9agcYG-" } }, { "cell_type": "code", "source": [ "class A:\n", " def process(self):\n", " print(\" In class A\")\n", "\n", "class B(A):\n", " def process(self):\n", " print(\" In class B\")\n", "\n", "class C(B, A):\n", " def process(self):\n", " print(\" In class C\")\n", "\n", "# Creating object of C class\n", "C1 = C()\n", "C1.process()\n", "print(C.mro())\n", "\n", "class Numbers:\n", " def __init__(self, a, b):\n", " self.a = a\n", " self.b = b\n", "\n", "\n", "class NumbersWithOperations(Numbers):\n", " def __init__(self, a, b):\n", " # Calling the initializer of the parent class.\n", " super().__init__(a, b)\n", "\n", " def sum(self):\n", " return self.a + self.b\n", "\n", " def prod(self):\n", " return self.a * self.b\n", "\n", "\n", "if __name__ == \"__main__\":\n", " two_numbers = NumbersWithOperations(5, 4)\n", " print(two_numbers.sum())\n", "\n", "class Top:\n", "\n", " def __init__(self):\n", "\n", " self.var1 = 1\n", " self.var2 = 2\n", "\n", "obj1 = Top() # Typical instantiation\n", "\n", "class Bottom:\n", "\n", " def __init__(self):\n", "\n", " self.composition = Top() # Composition (i.e., instantiation via an attribute)\n", "\n", "obj2 = Bottom() # Typical instantiation\n", "\n", "print(obj1.var1)\n", "print(obj2.composition.var2)\n", "obj2.composition.var1 = 5\n", "print(obj2.composition.var1)\n", "\n", "# Base class\n", "class Parent:\n", " def func1(self):\n", " print(\"This function is in parent class.\")\n", "\n", "# Derived class\n", "class Child(Parent):\n", " def func2(self):\n", " print(\"This function is in child class.\")\n", "\n", "# Driver code\n", "obj = Child()\n", "obj.func1()\n", "obj.func2()\n", "\n", "# Base class 1\n", "class Mother:\n", " mothername = \"\"\n", "\n", " def mother(self):\n", " print(self.mothername)\n", "\n", "# Base class 2\n", "class Father:\n", " fathername = \"\"\n", "\n", " def father(self):\n", " print(self.fathername)\n", "\n", "# Derived class\n", "class Son(Mother, Father):\n", " def parents(self):\n", " print(\"Father :\", self.fathername)\n", " print(\"Mother :\", self.mothername)\n", "\n", "# Driver code\n", "s1 = Son()\n", "s1.fathername = \"RAM\"\n", "s1.mothername = \"SITA\"\n", "s1.parents()\n", "\n", "# Base class\n", "class Grandfather:\n", " def __init__(self, grandfathername):\n", " self.grandfathername = grandfathername\n", "\n", "# Intermediate class\n", "class Father(Grandfather):\n", " def __init__(self, fathername, grandfathername):\n", " self.fathername = fathername\n", " # Call the constructor of Grandfather\n", " Grandfather.__init__(self, grandfathername)\n", "\n", "# Derived class\n", "class Son(Father):\n", " def __init__(self, sonname, fathername, grandfathername):\n", " self.sonname = sonname\n", " # Call the constructor of Father\n", " Father.__init__(self, fathername, grandfathername)\n", "\n", " def print_name(self):\n", " print('Grandfather name :', self.grandfathername)\n", " print('Father name :', self.fathername)\n", " print('Son name :', self.sonname)\n", "\n", "# Driver code\n", "s1 = Son('Prince', 'Rampal', 'Lal mani')\n", "print(s1.grandfathername)\n", "s1.print_name()\n", "\n", "# Base class\n", "class Parent:\n", " def func1(self):\n", " print(\"This function is in parent class.\")\n", "\n", "# Derived class 1\n", "class Child1(Parent):\n", " def func2(self):\n", " print(\"This function is in child 1.\")\n", "\n", "# Derived class 2\n", "class Child2(Parent):\n", " def func3(self):\n", " print(\"This function is in child 2.\")\n", "\n", "# Driver code\n", "object1 = Child1()\n", "object2 = Child2()\n", "\n", "object1.func1()\n", "object1.func2()\n", "object2.func1()\n", "object2.func3()\n", "\n", "# Base class\n", "class School:\n", " def func1(self):\n", " print(\"This function is in school.\")\n", "\n", "# Derived class 1 (Single Inheritance)\n", "class Student1(School):\n", " def func2(self):\n", " print(\"This function is in student 1.\")\n", "\n", "# Derived class 2 (Another Single Inheritance)\n", "class Student2(School):\n", " def func3(self):\n", " print(\"This function is in student 2.\")\n", "\n", "# Derived class 3 (Multiple Inheritance)\n", "class Student3(Student1, School):\n", " def func4(self):\n", " print(\"This function is in student 3.\")\n", "\n", "# Driver code\n", "obj = Student3()\n", "obj.func1()\n", "obj.func2()\n", "\n", "class Person:\n", " def show_name(self):\n", " print(\"Name: Alex\")\n", "\n", "class Student(Person):\n", " def show_course(self):\n", " print(\"Course: Python Programming\")\n", "\n", "# Creating object of Student class\n", "s = Student()\n", "s.show_name() # Inherited from Person\n", "s.show_course() # Defined in Student\n", "\n", "# Example of Single Inheritance in Python\n", "class Person:\n", " def display_name(self):\n", " print(\"Name: Sara\")\n", "\n", "class Student(Person):\n", " def display_course(self):\n", " print(\"Course: Python Programming\")\n", "\n", "# Using the child class\n", "s = Student()\n", "s.display_name() # Inherited from Person\n", "s.display_course() # Defined in Student\n", "\n", "\n" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "OYpIImqFcYPO", "outputId": "57b6d001-8755-4d5c-bccc-3327a008a8ea" }, "execution_count": 2, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ " In class C\n", "[, , , ]\n", "9\n", "1\n", "2\n", "5\n", "This function is in parent class.\n", "This function is in child class.\n", "Father : RAM\n", "Mother : SITA\n", "Lal mani\n", "Grandfather name : Lal mani\n", "Father name : Rampal\n", "Son name : Prince\n", "This function is in parent class.\n", "This function is in child 1.\n", "This function is in parent class.\n", "This function is in child 2.\n", "This function is in school.\n", "This function is in student 1.\n", "Name: Alex\n", "Course: Python Programming\n", "Name: Sara\n", "Course: Python Programming\n" ] } ] }, { "cell_type": "markdown", "source": [ "# **Python super() function**\n", "When a class inherits all properties and behavior from the parent class is called inheritance. In such a case, the inherited class is a subclass and the latter class is the parent class.\n", "\n", "In child class, we can refer to parent class by using the super() function. The super function returns a temporary object of the parent class that allows us to call a parent class method inside a child class method." ], "metadata": { "id": "Jeze5A0OcYcO" } }, { "cell_type": "code", "source": [ "# Parent class 1\n", "class Teacher:\n", " def teach(self):\n", " print(\"Teaches Math and Science\")\n", "\n", "# Parent class 2\n", "class Coach:\n", " def train(self):\n", " print(\"Trains in Football and Athletics\")\n", "\n", "# Child class inherits from both Teacher and Coach\n", "class Student(Teacher, Coach):\n", " def activities(self):\n", " print(\"Student is active in both academics and sports\")\n", " self.teach() # Calling method from Teacher\n", " self.train() # Calling method from Coach\n", "\n", "# Create object of Student\n", "s = Student()\n", "s.activities()\n", "\n", "# Base class\n", "class Grandparent:\n", " def show_grandparent(self):\n", " print(\"Grandparent: Shares wisdom\")\n", "\n", "# Intermediate class inheriting from Grandparent\n", "class Parent(Grandparent):\n", " def show_parent(self):\n", " print(\"Parent: Provides guidance\")\n", "\n", "# Child class inheriting from Parent\n", "class Child(Parent):\n", " def show_child(self):\n", " print(\"Child: Learns and grows\")\n", "\n", "# Create object of Child class\n", "c = Child()\n", "c.show_grandparent() # Inherited from Grandparent\n", "c.show_parent() # Inherited from Parent\n", "c.show_child() # Defined in Child\n", "\n", "# Parent class\n", "class Animal:\n", " def sound(self):\n", " print(\"Animals make different sounds\")\n", "\n", "# Child class 1\n", "class Dog(Animal):\n", " def bark(self):\n", " print(\"Dog: Barks\")\n", "\n", "# Child class 2\n", "class Cat(Animal):\n", " def meow(self):\n", " print(\"Cat: Meows\")\n", "\n", "# Creating objects of both child classes\n", "d = Dog()\n", "d.sound() # Inherited from Animal\n", "d.bark() # Defined in Dog\n", "\n", "c = Cat()\n", "c.sound() # Inherited from Animal\n", "c.meow() # Defined in Cat\n", "\n", "# Base class\n", "class Vehicle:\n", " def show_type(self):\n", " print(\"Vehicle: Used for transportation\")\n", "\n", "# First level child (single inheritance)\n", "class Car(Vehicle):\n", " def car_features(self):\n", " print(\"Car: Has 4 wheels and AC\")\n", "\n", "# Another base class for multiple inheritance\n", "class Electric:\n", " def battery_info(self):\n", " print(\"Electric: Runs on battery\")\n", "\n", "# Hybrid class (inherits from Car and Electric)\n", "class ElectricCar(Car, Electric):\n", " def features(self):\n", " print(\"ElectricCar: Eco-friendly and silent\")\n", "\n", "# Create object of ElectricCar\n", "ecar = ElectricCar()\n", "ecar.show_type() # Inherited from Vehicle\n", "ecar.car_features() # Inherited from Car\n", "ecar.battery_info() # Inherited from Electric\n", "ecar.features() # Defined in ElectricCar\n", "\n", "# Example using super() in Python Inheritance\n", "\n", "class Vehicle:\n", " def __init__(self):\n", " print(\"Vehicle is ready\")\n", "\n", "class Car(Vehicle):\n", " def __init__(self):\n", " super().__init__() # Calls the parent class constructor\n", " print(\"Car is ready\")\n", "\n", "# Creating object of Car class\n", "c = Car()\n", "\n", "class Parent:\n", " def __init__(self):\n", " self.parent_attribute = 'I am a parent'\n", "\n", " def parent_method(self):\n", " print('Back in my day...')\n", "\n", "\n", "# Create a child class that inherits from Parent\n", "class Child(Parent):\n", " def __init__(self):\n", " Parent.__init__(self)\n", " self.child_attribute = 'I am a child'\n", "\n", "\n", "# Create instance of child\n", "child = Child()\n", "\n", "# Show attributes and methods of child class\n", "print(child.child_attribute)\n", "print(child.parent_attribute)\n", "child.parent_method()\n", "\n", "\n", "class Parent:\n", " def __init__(self):\n", " self.parent_attribute = 'I am a parent'\n", "\n", " def parent_method(self):\n", " print('Back in my day...')\n", "\n", "\n", "# Create a child class that inherits from Parent\n", "class Child(Parent):\n", " def __init__(self):\n", " super().__init__()\n", " self.child_attribute = 'I am a parent'\n", "\n", "\n", "# Create instance of child\n", "child = Child()\n", "\n", "# Show attributes and methods of child class\n", "print(child.child_attribute)\n", "print(child.parent_attribute)\n", "child.parent_method()\n", "\n", "\n", "class B:\n", " def b(self):\n", " print('b')\n", "\n", "\n", "class C:\n", " def c(self):\n", " print('c')\n", "\n", "\n", "class D(B, C):\n", " def d(self):\n", " print('d')\n", "\n", "\n", "d = D()\n", "d.b()\n", "d.c()\n", "d.d()\n", "\n", "\n", "class B:\n", " def x(self):\n", " print('x: B')\n", "\n", "\n", "class C:\n", " def x(self):\n", " print('x: C')\n", "\n", "\n", "class D(B, C):\n", " pass\n", "\n", "\n", "d = D()\n", "d.x()\n", "print(D.mro())\n", "\n", "\n", "class Tokenizer:\n", " \"\"\"Tokenize text\"\"\"\n", " def __init__(self, text):\n", " print('Start Tokenizer.__init__()')\n", " self.tokens = text.split()\n", " print('End Tokenizer.__init__()')\n", "\n", "\n", "class WordCounter(Tokenizer):\n", " \"\"\"Count words in text\"\"\"\n", " def __init__(self, text):\n", " print('Start WordCounter.__init__()')\n", " super().__init__(text)\n", " self.word_count = len(self.tokens)\n", " print('End WordCounter.__init__()')\n", "\n", "\n", "class Vocabulary(Tokenizer):\n", " \"\"\"Find unique words in text\"\"\"\n", " def __init__(self, text):\n", " print('Start init Vocabulary.__init__()')\n", " super().__init__(text)\n", " self.vocab = set(self.tokens)\n", " print('End init Vocabulary.__init__()')\n", "\n", "\n", "class TextDescriber(WordCounter, Vocabulary):\n", " \"\"\"Describe text with multiple metrics\"\"\"\n", " def __init__(self, text):\n", " print('Start init TextDescriber.__init__()')\n", " super().__init__(text)\n", " print('End init TextDescriber.__init__()')\n", "\n", "\n", "td = TextDescriber('row row row your boat')\n", "print('--------')\n", "print(td.tokens)\n", "print(td.vocab)\n", "print(td.word_count)\n" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "7EhPFOWmcYjf", "outputId": "2e7a220c-281f-4e61-ef84-ed66ef1ac4ac" }, "execution_count": 3, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Student is active in both academics and sports\n", "Teaches Math and Science\n", "Trains in Football and Athletics\n", "Grandparent: Shares wisdom\n", "Parent: Provides guidance\n", "Child: Learns and grows\n", "Animals make different sounds\n", "Dog: Barks\n", "Animals make different sounds\n", "Cat: Meows\n", "Vehicle: Used for transportation\n", "Car: Has 4 wheels and AC\n", "Electric: Runs on battery\n", "ElectricCar: Eco-friendly and silent\n", "Vehicle is ready\n", "Car is ready\n", "I am a child\n", "I am a parent\n", "Back in my day...\n", "I am a parent\n", "I am a parent\n", "Back in my day...\n", "b\n", "c\n", "d\n", "x: B\n", "[, , , ]\n", "Start init TextDescriber.__init__()\n", "Start WordCounter.__init__()\n", "Start init Vocabulary.__init__()\n", "Start Tokenizer.__init__()\n", "End Tokenizer.__init__()\n", "End init Vocabulary.__init__()\n", "End WordCounter.__init__()\n", "End init TextDescriber.__init__()\n", "--------\n", "['row', 'row', 'row', 'your', 'boat']\n", "{'your', 'boat', 'row'}\n", "5\n" ] } ] }, { "cell_type": "markdown", "source": [ "# **Benefits of using the super() function.**\n", "\n", "We are not required to remember or specify the parent class name to access its methods.\n", "We can use the super() function in both single and multiple inheritances.\n", "The super() function support code reusability as there is no need to write the entire function" ], "metadata": { "id": "011admNkcYr3" } } ] }