The document discusses the concepts of inheritance and polymorphism in Python, providing examples of how to create classes and utilize them effectively. It covers single and multiple inheritance, constructor and method overriding, as well as polymorphism through method overloading and duck typing. The document includes Python code examples to illustrate these concepts in practice.
Significance Of Inheritance Example-1:teacher.py # A Python program to create Teacher class and store it into teacher.py module. # This is Teacher class. save this code in teaccher.py file class Teacher: def setid(self, id): self.id = id def getid(self): return self.id def setname(self, name): self.name = name def getname(self): return self.name def setaddress(self, address): self.address = address def getaddress(self): return self.address def setsalary(self, salary): self.salary = salary def getsalary(self): return self.salary When the programmer wants to use this Teacher class that is available in teachers.py file, he can simply import this class into his program and use it
4.
Significance Of Inheritance Program #using Teacher class from teacher important Teacher from teacher import Teacher # create instance t = Teacher() # store data into the instance t.setid(10) t.setname("Ram") t.setaddress('HNO-10, Raj gardens, Delhi') t.setsalary(25000.50) # retrive data from instance and display print('id= ', t.getid()) print('name= ', t.getname()) print('address= ', t.getaddress()) print('salary= ', t.getsalary())
Significance Of Inheritance Example-2:student.py # A Python program to create sudent class and store it into student.py module class Student: def setid(self, id): self.id = id def getid(self): return self.id def setname(self, name): self.name = name def getname(self): return self.name def setaddress(self, address): self.address = address def getaddress(self): return self.address def setmarks(self, marks): self.marks = marks def getmarks(self): return self.marks Now, the second programmer who created this Student class and saved it as student.py can use it whenever he needs.
7.
Significance Of Inheritance Program #using student class from student import student from student import Student # create instance s = Student() # store data into the instance s.setid(100) s.setname('Rakesh') s.setaddress('HNO-22, Ameerpet, Hyderabad') s.setmarks(970) #Print the data print("ID: ", s.getid()) print("Name: ", s.getname()) print("Address: ", s.getaddress()) print("Marks: ", s.getmarks())
8.
Significance Of Inheritance Comparision classTeacher: def setid(self, id): self.id = id def getid(self): return self.id def setname(self, name): self.name = name def getname(self): return self.name def setaddress(self, address): self.address = address def getaddress(self): return self.address def setsalary(self, salary): self.salary = salary def getsalary(self): return self.salary class Student: def setid(self, id): self.id = id def getid(self): return self.id def setname(self, name): self.name = name def getname(self): return self.name def setaddress(self, address): self.address = address def getaddress(self): return self.address def setmarks(self, marks): self.marks = marks def getmarks(self): return self.marks By comparing both the codes, we can observe 75% of the code is common
9.
Significance Of Inheritance fromteacher import Teacher class Student(Teacher): def setmarks(self, marks): self.marks = marks def getmarks(self): return self.marks # create instance s = Student() # store data into the instance s.setid(100) s.setname('Rakesh') s.setaddress('HNO-22, Ameerpet, Hyderabad') s.setmarks(970) #Print the data print("ID: ", s.getid()) print("Name: ", s.getname()) print("Address: ", s.getaddress()) print("Marks: ", s.getmarks()) Syntax: class Subclass(Baseclass):
10.
Significance Of Inheritance Advantages Smallerand easier to develop Productivity increases marks setmarks(), getmarks() id name address salary setid(), getid() setname(), getname() setaddress(), getaddress() setsalary(), getsalary() Student class Object Copy of Teacher class object s
11.
Inheritance Definition Deriving the newclasses from the existing classes such that the new classes inherit all the members of the existing classes is called Inheritance Syntax: class Subclass(Baseclass):
Constructors in Inheritance Example Likevariables & Methods, the constructors in the super class are also available in the sub-class class Father: def __init__(self): self.property = 800000.00 def display_property(self): print('Father's property= ',self.property) #Create the instance s = Son() s.display_property() class Son(Father): pass # we do not want to write anything in the sub class
Overriding super class Constructors+ Methods Constructor Overriding - The sub-class constructor is replacing the super class constructor Method Overriding - The sub-class method is replacing the super class method Example # overriding the base class constructor and method in sub class class Father: def __init__(self): self.property = 800000.00 def display_property(self): print('Father's property= ', self.property) class Son(Father): def __init__(self): self.property = 200000.00 def display_property(self): print('child's property= ', self.property) # create sub class instance and display father's property s = Son() s.display_property()
The super() Method super()is a built-in method which is useful to call the super class constructor or Methods Examples #Call super class constructors super().__init__() #Call super class constructors and pass arguments super().__init__(arguments) #Call super class method super().method()
18.
The super() Method Example Example-1 #acceessing base class constructor in sub class class Father: def __init__(self, property=0): self.property = property def display_property(self): print('Father's property= ', self.property) class Son(Father): def __init__(self, property1=0, property=0): super().__init__(property) self.property1 = property1 def display_property(self): print('Total property of child= ', self.property1 + self.property) # create sub class instance and display father's property s = Son(200000.00, 800000.00) s.display_property()
19.
The super() Method Example Example-2 #Accessing base class constructor and method in the sub class class Square: def __init__(self, x): self.x = x def area(self): print('Area of square= ',self.x * self.x) class Rectangle(Square): def __init__(self, x, y): super().__init__(x) self.y = y def area(self): super().area() print('Area of rectangle= ',self.x * self.y) # find areas of square and rectangle a, b = [float(x) for x in input("Enter two measurements: ").split()] r = Rectangle(a,b) r.area()
Types of Inheritance Single Bank AndhraBankStateBank # A Python program showing single inhertiance in which two sub classes are derived from a single base class. # single inhertiance class Bank(object): cash = 100000000 @classmethod def available_cash(cls): print(cls.cash) class StateBank(Bank): cash = 200000000 @classmethod def available_cash(cls): print(cls.cash + Bank.cash) class AndhraBank(Bank): pass a = AndhraBank() a.available_cash() s = StateBank() s.available_cash()
22.
Types of Inheritance Multiple FatherMother # A Python program to implement multiple inhertiance using two base classes #multiple inheritance class Father: def height(self): print('Height is 6.0 foot') class child(Father, Mother): pass class Mother: def color(self): print('color is brown') c = child() print('child's inherited qualities: ') c.height() c.color() Child Syntax: class Subclass(BaseClass1, BaseClass2, ...):
23.
Multiple Inheritance Problems inMI # A Python program to prove that only one class constructor is available to sub class in multiple inheritance. # when super classes have constructors class A(object): def __init__(self): self.a = 'a' print(self.a) class B(object): def __init__(self): self.b = 'b' print(self.b) class C(A, B): def __init__(self): self.c = 'c' print(self.c) super().__init__() # access the super class instance vars from C o = C() # o is object of class C
24.
Multiple Inheritance Solutions #A Pythonprogram to access all the instance variables of both the base classes in multiple inheritance. # when super classes have constructors - v2.0 class A(object): def __init__(self): self.a = 'a' print(self.a) super().__init__() class B(object): def __init__(self): self.b = 'b' print(self.b) super().__init__() class C(A,B): def __init__(self): self.c = 'c' print(self.c) super().__init__() # access the super class instance vars from C o = C() # o is object class C Object A B C
MRO In Multiple Inheritance,any specified attribute or method is searched first in the current class. If not found, the search continues into parent classes in depth-first left to right fasion without searching for the same class twice 1. The first principle is to search for the sub classes before going for its base classes. Thus if class B is inherited from A, it will search B first and then goes to A 2. The second principle is that when a class is inherited from several classes, it searches in the order from left to right in the base class. Example: class C(A, B), then first it will search in A and then in B 3. The third principle is that it will not visit any class more than once. That means a class in the inheritance hierarchy is traversed only once exactly
MRO Program # A Pythonprogram to understand the order of execution of methods in several base classes according to MRO. class A(object): def method(self): print('A class method') super().method() class B(object): def method(self): print('B class method') super().method() class C(object): def method(self): print('C class method') class X(A, B): def method(self): print('X class method') super().method() class Y(A, B): def method(self): print('Y class method') super().method() class P(X,Y,C): def method(self): print('P class method') super().method() P = P() P.method() P.mro(): Returns sequence of execution of classes
Polymorphism Duck Typing Philosophy Datatypeof the variables is not explicitly declared type(): To check the type of variable or object Example-1 x = 5 print(type(x)) <class ‘int’> Example-2 x = “Hello” print(type(x)) <class ‘str’> Conclusion 1. Python’s type system is strong because every variable or object has a type that we can check with the type() function 2. Python’s type system is ‘dynamic’ since the type of a variable is not explicitly declared, but it changes with the content being stored
33.
Polymorphism Duck Typing Philosophy:Program # A Python program to invoke a method on an object without knowing the type (or class) of the object. # duck typing example # Duck class contains talk() method class Duck: def talk(self): print('Quack, quack!') #Human class contains talk() method class Human: def talk(self): print('Hello, hi!') # this method accepts an object and calls talk() method def call_talk(obj): obj.talk() # call call_talk() method pass an object # depending on type of object, talk() method is executed x = Duck() call_talk(x) x = Human() call_talk(x) During runtime, if it is found that method does not belong to that object, there will be an error called ‘AttributeError’
34.
Polymorphism Attribute Error: Overcoming #this method accepts an object and calls talk() method def call_talk(obj): if hasattr(obj, 'talk'): obj.talk() elif hasattr(obj, 'bark'): obj.bark() else: print('Wrong object passed...') During runtime, if it is found that method does not belong to that object, there will be an error called ‘AttributeError’
Operator Overloading Example-1 # APython program to use addition operator to act on different types of objects. # overloading the + operator # using + on integers to add them print(10+15) #using + on strings to concatenate them s1 = "Red" s2 = "Fort" print(s1+s2) #using + on lists to make a single list a = [10, 20, 30] b = [5, 15, -10] print(a+b) ‘+’ operator is overloaded and thus exhibits polymorphism
Operator Overloading Example-1 # APython program to show method overloading to find sum of two or three numbers. # method overloading class Myclass: def sum(self, a=None, b=None, c=None): if a!=None and b!=None and c!=None: print('Sum of three= ', a + b + c) elif a!=None and b!=None: print('Sum of two= ', a + b) else: print('Please enter two or three arguments') # call sum() using object m = Myclass() m.sum(10, 15, 20) m.sum(10.5, 25.55) m.sum(100) If a method is written such that it can perform more than one task, it is called method overloading
Operator Overriding Example-1 # APython program to override the super class method in sub class. # method overriding import math class Square: def area(self, x): print('Square area= %.4f' % (x * x)) class Circle(Square): def area(self, x): print('Circle area= %.4f' % (math.pi *x * x)) # call area() using sub class object c = Circle() c.area(15) If a method written in sub class overrides the same method in super class, then it is called method overriding Method overriding already discussed in Constructor & Method Overridings