SlideShare a Scribd company logo
1 of 49
Download to read offline
you must specify self explicitly when defining the method, you don’t
include it when calling the method
Classes are defined using keyword “Class”
followed by user defined “ClassName” and a
colon.
Variables are also called attributes
Functions are also called methods.
Functions are also called methods.
Syntax: class className:
<statement-1>
<statement-2>
;
<statement-n>
 class Mobile:
 def __init__(self, name):
 self.mobile_name=name
 print("Constructor")
 def receive_msg(self):
 print(f"Receive Message from {self.mobile_name}")
 def send_msg(self):
 print(f"Send Message from {self.mobile_name}")
 def main():
 def main():
 nokia = Mobile("Nokia")
 nokia.receive_msg()
 nokia.send_msg()
 if __name__=="__main__":
 main()
 Output:
 Constructor
 Receive Message from Nokia
 Send Message from Nokia
•Class Mobile has 2 methods:
-Receive_msg()
- Send_msg()
•Self has no meaning in Python.
•It is used to improve readability.
•__init__ function is called when an
object is instantiated
 Object refers to a particular instance of a class.
 It contains variables and methods defined in the class.
 Class objects support 2 kinds of operations.
◦ A. Attribute references – The names in class are referenced by
objects and are called attribute references. There are two
objects and are called attribute references. There are two
kinds of attribute references.
 A. Data attributes – Variables defined within methods are called
instance variables / data attributes which are used to store data.
 B. Method attributes – Functions that are inside a class and are
referenced by objects of a class.
B. Instantiation – Act of creating an object from a class.
 class student:
 def __init__(self,name,marks):
 self.name = name
 self.marks = marks
 def check_pass_fail(self):
 if self.marks >= 40:
 return True
 else:
 return False
•Student1 and Student2 are the objects of
Student Class.
•Student1 is instantiated with name as Harry
and marks 30
•Student2 is instantiated with name as Jane
and marks 99
•Whenever you call a method using an object,
 def main():
 student1 = student("Harry", 30)
 student2 = student("Jane", 99)
 did_pass = student1.check_pass_fail()
 print(did_pass)
 did_pass = student2.check_pass_fail()
 print(did_pass)
 if __name__=="__main__":
 main()
•Whenever you call a method using an object,
the object is automatically passed in as the
first parameter to the self parameter variable
Output
False
True
 class Birds:
 def __init__(self, bird_name):
 self.bird_name = bird_name
 def flying_birds(self):
 print(f"{self.bird_name} flies above clouds")
 def non_flying_birds(self):
 print(f"{self.bird_name} is the national bird of Australia")
 def main():
 vulture=Birds("Griffon Vulture")
 Crane = Birds("Common Crane")
 Emu = Birds("Emu")
 vulture.flying_birds()
 Crane.flying_birds()
 Emu.non_flying_birds()
 if __name__=="__main__":
 main()
Output:
Griffon Vulture flies above clouds
Common Crane flies above clouds
Emu is the national bird of Australia
vulture, Crane and Emu are the objects
of class Birds
 Only one constructor can be defined per class
 Syntax:
 def __init__(self,parameter_1,….parameter_n)
 It defines and initializes the instance variables
It is called as soon as an object of a class is
 It is called as soon as an object of a class is
instantiated.
 All the data attributes of a class are initialised
in the init function itself.
 An object can be passed as an argument to a calling
function
 class Music:
 def __init__(self,song,artist):
 self.song=song
 self.artist=artist
def print_track_info(vocalist):
Output:
Song is Boy With Love
Artist is BTS2
 def print_track_info(vocalist):
 print(f"Song is {vocalist.song}")
 print(f"Artist is {vocalist.artist}")
 singer = Music("Boy With Love","BTS")
 print_track_info(singer)
 class sum:
 def __init__(self,num1,num2):
 self.num1 = num1
 self.num2 = num2
 self.sum =" "
 def add_sum(self):
 self.sum = self.num1 + self.num2
 return self
Output:
9
1787802679712
True
 return self
 def main():
 number =sum(4,5)
 returned_object = number.add_sum()
 print(returned_object.sum)
 print(id(returned_object))
 print(isinstance(returned_object,sum))
 if __name__=="__main__":
 main()
•id(object) is a function that is used to find
the identity of the location of the object in
memory
•Isinstance(object,classinfo) is a function
that returns a boolean stating if the object
is an instance of class or not.
 class Dog:
 kind ='Canine'
 def __init__(self,name):
 self.dog_name=name
Class Attributes:
Are Class variables that is
shared by all objects of a
class.
Data Attributes
Are instance variables
unique to each object of a
 d=Dog('Fido')
 e=Dog("Buddy")
 print(f"{d.kind}")
 print(f"{e.kind}")
 print(f"{d.dog_name}")
 print(f"{e.dog_name}")
Output:
Canine
Canine
Fido
Buddy
unique to each object of a
class.
 Encapsulation -> Information hiding
 Abstraction -> Implementation hiding
 It is the process of combining variables that store data and
methods that work on those variables into a single unit called
class.
 class foo:
 def __init__(self,a,b):
 self.a = a
Output:
7
 self.a = a
 self.b = b
 def add(self):
 return self.a + self.b
 foo_object =foo(3,4)
 print(foo_object.add())
The internal representation of the foo
class is hidden outside the class ->
Encapsulation
The implementation of add() function
is hidden from the object. ->
Abstraction
 class Demo:
 def __init__(self):
 self.nonprivate="I am not a private instance"
 self.__private="I am a private instance"
 def display_privateinstance(self):
 print(f"{self.__private} used within the method of a class")
def main():
 def main():
 demo_obj = Demo()
 demo_obj.display_privateinstance()
 print(demo_obj.nonprivate)
 # print(demo_obj.__private)
 if __name__=="__main__":
 main()
Output:
I am a private instance used within
the method of a class
I am not a private instance
 The private instance variables cannot be accessed outside the
class, but only through a method defined inside the class
 In Python, an identifier with double underscore is treated as
private.
 Name mangling is intended to give the class an easy way to
define private instance variables and methods
 class Student:
 def __init__(self, name):
 self.__name = name // private attribute

 s1 = Student("Santa")
 print(s1._Student__name)
 //Access using _class__private attribute
 The class that is used as the basis for inheritance is called
a superclass or base class.
 A class that inherits from a base class is called a subclass
or derived class.
 The base class and derived class exhibit “is a” relationship
in inheritance
 Eg: Sitar is a stringed instrument
 Eg: Sitar is a stringed instrument
 Syntax of derived class:
 Class DerivedClassName(BaseClassName):
 <statement-1>
 .
 .
 <statement-N>
 It is possible to define the derived base when the base class is defined in another
module.
 Class DerivedClassName(modname.BaseClassName)
 # module1.py
 class Hello:
 def show(self):
 print("Module1.Hello.Show Welcome")
 print("Module1.Hello.Show Welcome")
 #modulederived.py
 ______________________________________________________________________________________
import module1
 class derived_module1(module1.Hello): # derived class of the Hello class in Module 1
 def derived_class(self):
 print("Hi")
 def main():
 check = derived_module1() # object of the derived_module1 class
 check.show()
 if __name__=="__main__":
 main() Output:
Module1.Hello.Show Welcome
 class someclass(object): # this is derived out of the "class object"
 def __init__(self):
 print("Constructor")
 def someclass_function(self):
 print("Hello India")
•All class except “Class object” are
derived classes.
•Class object is the base of
inheritance hierarchy and hence
has no derived classes.
 def main():
 obj = someclass()
 obj.someclass_function()
 if __name__=="__main__":
 main()
has no derived classes.
•Classes without baseclassname are
derived from the class object.
 class cricket:
 def __init__(self,IPLteam,owner,times_won):
 self.IPLteam = IPLteam
 self.owner = owner
 self.times_won = times_won
 def IPLOwner(self):
 print(f"The IPL team {self.IPLteam} is owned by {self.owner}")
 class derived_cricket(cricket):
 class derived_cricket(cricket):
 def IPLresults(self):
 print(f"The IPL team {self.IPLteam} has won {self.times_won}")
 def main():
 cricket_fans=derived_cricket("KKR","SRK", 9)
 cricket_fans.IPLOwner()
 cricket_fans.IPLresults()
 if __name__=="__main__":
 main()
Output:
The IPL team KKR is
owned by SRK
The IPL team KKR has
won 9
 Derived_cricket is the derived class and cricket is the base
class
 Derived class inherits variables and methods of base class
 __init__() method is also derived from base class. Derived
 __init__() method is also derived from base class. Derived
class has access of __init__() method of the base class.
 The base class has 3 data attributes, IPLteam, owner and
times_won. It has a method IPLOwner
 Derived class has access to the data attributes and methods
of the base class.
 In Single Inheritance, built-in super() function is used to refer to base
class without explicitly naming it.
 If derived class has __init__() method and needs to access the base class
__init__() method explicitly, then this is done using super().
 If the derived class needs no attributes from base class, then we do not
need to use super() method to invoke base class __init__() method.
need to use super() method to invoke base class __init__() method.
 Super().__init__(base_class_parameters)
 Its usage is as below.
 Class DerivedClass(BaseClass):
 def__init__(self, derived_class_params, base_class_params)
 super().__init__(base_class_params)
 self.derived_class_params = derived_class_params
 class country:
 def __init__(self,country_name):
 self.country_name = country_name
 def country_details(self):
 print(f"Happiest country in world is {self.country_name}")
 class HappyCountry(country):
 def __init__(self,country_name,continent):
 super().__init__(country_name)
 self.continent = continent
 self.continent = continent
 def Happy_Country_Details(self):
 print(f"Happiest country in the world is {self.country_name} and it is in {self.continent}")
 def main():
 obj = HappyCountry("Finland","Europe")
 obj.Happy_Country_Details()
 if __name__=="__main__":
 main()
Output:
Happiest country in the world
is Finland and it is in Europe
 The derived class __init__() method has its own parameters
plus the base class parameters.
 We do not need to specify self for base class init() method
 Base class methods may be overridden (method overriding)
 Derived class should have a method with same name as those
in base class. Also signature (method name, order and total
number of parameters) should be same.
def main():
print("Derived Class")
derived_obj=Friction("R K Narayan",
"Malgudi Days", "India Book House")
derived_obj.book_info()
print("-----------------------")
derived_obj.invoke_base_class_method()
class Book:
 def __init__(self,author,title):
 self.author = author
 self.title = title
 def book_info(self):
 print(f"{self.title} is authored by {self.author}")
class Friction(Book):
if __name__=="__main__":
main()
Output:
Derived Class
Malgudi Days is authored by R K Narayan and
published by India Book House
-----------------------
Malgudi Days is authored by R K Narayan
class Friction(Book):
 def __init__(self,author,title,publisher):
 super().__init__(author,title)
 self.publisher = publisher
 def book_info(self):
 print(f"{self.title} is authored by {self.author} and published by {self.publisher}")
 def invoke_base_class_method(self):
 super().book_info()
 Python supports a form of multiple inheritances. A derived class
definition with multiple base classes looks like
 Class DerivedClassName(Base_1,Base_2, Base_3)
 <statement_1>
 .
 .
 <statement_N>
The baseclass method can be invoked from the derived class using the
 The baseclass method can be invoked from the derived class using the
syntax
 BaseClassName.methodname (self, arguments)
 Issubclass(DerivedClassName, BaseClassName)
 returns True if DerivedClassName is a derived class of base class
BaseClassName.
 class length:
 l = 0
 def length(self):
 return self.l
 class breadth:
 b = 0
 def breadth(self):
 return self.b
 class rect_area(length, breadth): # derived from class length and class breadth
Output:
Enter the required length for rectangle: 5
Enter the required breadth for rectangle: 4
The area of rectangle with length 5 units
and breadth 4 units is 20 sq. units.
 class rect_area(length, breadth): # derived from class length and class breadth
 def r_area(self):
 print("The area of rectangle with length "+str(self.l)+" units and breadth "+
 str(self.b)+" units is "+str(self.l * self.b)+" sq. units.")
 def main():
 o = rect_area()
 o.l = int(input("Enter the required length for rectangle: "))
 o.b = int(input("Enter the required breadth for rectangle: "))
 o.r_area()
 if __name__=="__main__":
 main()
 class Pet:
 def __init__(self,breed):
 self.breed = breed
 def about(self):
 print(f"This is {self.breed} breed")
 class Insurable:
 def __init__(self,amount):
 self.amount = amount
def main():
dog_obj = dog(15, "Shitzu", 5000)
dog_obj.about()
dog_obj.get_weight()
if __name__=="__main__":
main()
 self.amount = amount
 def about(self):
 print(f"It is insured for an amount {self.amount}")
 class dog(Pet, Insurable):
 def __init__(self,weight,breed,amount):
 self.weight = weight
 Pet.__init__(self,breed)
 Insurable.__init__(self,amount)
 def get_weight(self):
 print(f" {self.breed} dog weights around {self.weight} pounds")
Output:
This is Shitzu breed
Shitzu dog weights around 15 pounds
[<class '__main__.dog'>, <class
'__main__.Pet'>, <class
'__main__.Insurable'>, <class 'object'>]
 MRO denotes the way Python programming
language resolves a method found in multiple
base classes.
 Syntax : class_name.mro()
 Syntax : class_name.mro()
 It uses C3 linearization algorithm to
determine the order of the methods to be
invoked in multiple inheritances
 class First:
 def my_method(self):
 print("You found me in class first")
 class Second:
 def my_method(self):
 print("you found me in class second")
 class Third:
 def my_method(self):
def main():
obj = Sixth()
obj.my_method()
print(Sixth.mro())
if __name__=="__main__":
main()
 print("you found me in class Third")
 class Fourth(Third,First):
 pass
 class Fifth(Third, Second):
 pass
 class Sixth(Fifth, Fourth):
 pass
Output:
you found me in class Third
[<class '__main__.Sixth'>, <class
'__main__.Fifth'>, <class '__main__.Fourth'>,
<class '__main__.Third'>, <class
'__main__.Second'>, <class '__main__.First'>,
<class 'object'>]
 class First:
 def __init__(self):
 print("In First")
 super().__init__()
 class Second:
 def __init__(self):
 print("In Second")
 super().__init__()
Output:
In Third
In First
In Second
Method Resolution order is [<class
'__main__.Third'>, <class '__main__.First'>,
<class '__main__.Second'>, <class
'object'>]
 class Third (First,Second):
 def __init__(self):
 print("In Third")
 super().__init__()
 def main():
 obj = Third()
 print(f"Method Resolution order is {Third.mro()}")
 if __name__=="__main__":
 main()
First the __init__() method of class Third is called.
This prints “In Third”. After this super().__init__() is
called which in turn calls the __init__() method of
the next class found in MRO.
 import math
 pi = 3.141
 class square:
 def __init__(self, length):
 self.l = length
 def perimeter(self):
 return 4 * (self.l)
 def area(self):
 return self.l * self.l
 class Circle:
 def __init__(self, radius):
•Square and Circle are the derived classes
•The derived classes have the methods
perimeter() and area() which are common to
both
•But the implementation of these two
methods is different in each of the 2 classes.
 def __init__(self, radius):
 self.r = radius
 def perimeter(self):
 return 2 * pi * self.r
 def area(self):
 return pi * self.r ** 2
 # Initialize the classes
 sqr = square(10)
 c1 = Circle(4)
 print("Perimeter computed for square: ", sqr.perimeter())
 print("Area computed for square: ", sqr.area())
 print("Perimeter computed for Circle: ", c1.perimeter())
 print("Area computed for Circle: ", c1.area())
Output:
Perimeter computed for square: 40
Area computed for square: 100
Perimeter computed for Circle: 25.128
Area computed for Circle: 50.256
 This is a specific case of Polymorphism.
 “Poly” means many and “morphism” means
forms. You can have multiple classes where
each class implements the same variables or
methods in different ways.
methods in different ways.
 Operator overloading is a specific case of
polymorphism, where an operator can have
different meaning when used with operands
of different types.
 class Rectangle:
 def __init__(self,width,height):
 self.width = width
 self.height = height
 def __gt__(self,other):
 rectangle_l_area = self.width * self.height
 rectangle_2_area = other.width * other.height
 return rectangle_l_area > rectangle_2_area
Output:
rectangle 1 is greater than
rectangle 2
 def main():
 rectangle_1_obj = Rectangle(5,10)
 rectangle_2_obj = Rectangle(3,4)
 if rectangle_1_obj > rectangle_2_obj:
 print("rectangle 1 is greater than rectangle 2")
 else:
 print("rectangle 2 is greater than rectangle 1")
 if __name__=="__main__":
 main()
•rectangle_1_obj and rectangle_2_obj are objects of the
Rectangle class.
•When the expression rectangle_l_area > rectangle_2_area
is evaluated, then the method
rectangle_1_obj.__gt__(rectangle_2_obj) gets invoked.
 class Complex:
 def __init__(self,real,imaginary):
 self.real = real
 self.imaginary = imaginary
 def __add__(self,other):
 return Complex (self.real + other.real, self.imaginary + other.imaginary)
 def __str__(self):
 return f"{self.real} + i{self.imaginary}"
 return f"{self.real} + i{self.imaginary}"
 def main():
 complex_number_1 = Complex(4,5)
 complex_number_2 = Complex(2,3)
 complex_number_sum = complex_number_1 + complex_number_2
 print(f"{complex_number_1} + {complex_number_2} =
{complex_number_sum}")
 if __name__=="__main__":
 main()
 complex_number_sum = complex_number_1 +
complex_number_2 will execute as
 Complex_number_1.__add__(complex_number_2)
 __add__() method is called magic method.
 Whenever we have to print the complex_number formatted,
 Whenever we have to print the complex_number formatted,
then __str__() magic method is called which is implemented as
shown in the program
 The __str__() method returns the values of real and imaginary
data concatenated together and imaginary part is prefixed with
i.
Object_Oriented_Programming_Unit3.pdf

More Related Content

Similar to Object_Oriented_Programming_Unit3.pdf

Python programming computer science and engineering
Python programming computer science and engineeringPython programming computer science and engineering
Python programming computer science and engineeringIRAH34
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیMohammad Reza Kamalifard
 
Basic_concepts_of_OOPS_in_Python.pptx
Basic_concepts_of_OOPS_in_Python.pptxBasic_concepts_of_OOPS_in_Python.pptx
Basic_concepts_of_OOPS_in_Python.pptxsantoshkumar811204
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Threeamiable_indian
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc csKALAISELVI P
 
Empower your App by Inheriting from Odoo Mixins
Empower your App by Inheriting from Odoo MixinsEmpower your App by Inheriting from Odoo Mixins
Empower your App by Inheriting from Odoo MixinsOdoo
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethodsdreampuf
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfSudhanshiBakre1
 
Python decorators
Python decoratorsPython decorators
Python decoratorsAlex Su
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfSudhanshiBakre1
 
Python Descriptors Demystified
Python Descriptors DemystifiedPython Descriptors Demystified
Python Descriptors DemystifiedChris Beaumont
 
Pyimproved again
Pyimproved againPyimproved again
Pyimproved againrik0
 
Python – Object Oriented Programming
Python – Object Oriented Programming Python – Object Oriented Programming
Python – Object Oriented Programming Raghunath A
 
Chap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptChap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptmuneshwarbisen1
 
601109769-Pythondyttcjycvuv-Inheritance .pptx
601109769-Pythondyttcjycvuv-Inheritance .pptx601109769-Pythondyttcjycvuv-Inheritance .pptx
601109769-Pythondyttcjycvuv-Inheritance .pptxsrinivasa gowda
 

Similar to Object_Oriented_Programming_Unit3.pdf (20)

Python programming computer science and engineering
Python programming computer science and engineeringPython programming computer science and engineering
Python programming computer science and engineering
 
Python session 7 by Shan
Python session 7 by ShanPython session 7 by Shan
Python session 7 by Shan
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
 
Basic_concepts_of_OOPS_in_Python.pptx
Basic_concepts_of_OOPS_in_Python.pptxBasic_concepts_of_OOPS_in_Python.pptx
Basic_concepts_of_OOPS_in_Python.pptx
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
 
Spsl vi unit final
Spsl vi unit finalSpsl vi unit final
Spsl vi unit final
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc cs
 
Empower your App by Inheriting from Odoo Mixins
Empower your App by Inheriting from Odoo MixinsEmpower your App by Inheriting from Odoo Mixins
Empower your App by Inheriting from Odoo Mixins
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethods
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
 
Python decorators
Python decoratorsPython decorators
Python decorators
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
 
Python Descriptors Demystified
Python Descriptors DemystifiedPython Descriptors Demystified
Python Descriptors Demystified
 
Pyimproved again
Pyimproved againPyimproved again
Pyimproved again
 
Python – Object Oriented Programming
Python – Object Oriented Programming Python – Object Oriented Programming
Python – Object Oriented Programming
 
Unit - 3.pptx
Unit - 3.pptxUnit - 3.pptx
Unit - 3.pptx
 
Chap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptChap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.ppt
 
601109769-Pythondyttcjycvuv-Inheritance .pptx
601109769-Pythondyttcjycvuv-Inheritance .pptx601109769-Pythondyttcjycvuv-Inheritance .pptx
601109769-Pythondyttcjycvuv-Inheritance .pptx
 

More from Koteswari Kasireddy

Chapter-7-Sampling & sampling Distributions.pdf
Chapter-7-Sampling & sampling Distributions.pdfChapter-7-Sampling & sampling Distributions.pdf
Chapter-7-Sampling & sampling Distributions.pdfKoteswari Kasireddy
 
Relational Model and Relational Algebra.pptx
Relational Model and Relational Algebra.pptxRelational Model and Relational Algebra.pptx
Relational Model and Relational Algebra.pptxKoteswari Kasireddy
 
Unit 4 chapter - 8 Transaction processing Concepts (1).pptx
Unit 4 chapter - 8 Transaction processing Concepts (1).pptxUnit 4 chapter - 8 Transaction processing Concepts (1).pptx
Unit 4 chapter - 8 Transaction processing Concepts (1).pptxKoteswari Kasireddy
 
Database System Concepts AND architecture [Autosaved].pptx
Database System Concepts AND architecture [Autosaved].pptxDatabase System Concepts AND architecture [Autosaved].pptx
Database System Concepts AND architecture [Autosaved].pptxKoteswari Kasireddy
 
Control_Statements_in_Python.pptx
Control_Statements_in_Python.pptxControl_Statements_in_Python.pptx
Control_Statements_in_Python.pptxKoteswari Kasireddy
 
parts_of_python_programming_language.pptx
parts_of_python_programming_language.pptxparts_of_python_programming_language.pptx
parts_of_python_programming_language.pptxKoteswari Kasireddy
 

More from Koteswari Kasireddy (20)

DA Syllabus outline (2).pptx
DA Syllabus outline (2).pptxDA Syllabus outline (2).pptx
DA Syllabus outline (2).pptx
 
Chapter-7-Sampling & sampling Distributions.pdf
Chapter-7-Sampling & sampling Distributions.pdfChapter-7-Sampling & sampling Distributions.pdf
Chapter-7-Sampling & sampling Distributions.pdf
 
unit-3_Chapter1_RDRA.pdf
unit-3_Chapter1_RDRA.pdfunit-3_Chapter1_RDRA.pdf
unit-3_Chapter1_RDRA.pdf
 
DBMS_UNIT_1.pdf
DBMS_UNIT_1.pdfDBMS_UNIT_1.pdf
DBMS_UNIT_1.pdf
 
business analytics
business analyticsbusiness analytics
business analytics
 
Relational Model and Relational Algebra.pptx
Relational Model and Relational Algebra.pptxRelational Model and Relational Algebra.pptx
Relational Model and Relational Algebra.pptx
 
CHAPTER -12 it.pptx
CHAPTER -12 it.pptxCHAPTER -12 it.pptx
CHAPTER -12 it.pptx
 
WEB_DATABASE_chapter_4.pptx
WEB_DATABASE_chapter_4.pptxWEB_DATABASE_chapter_4.pptx
WEB_DATABASE_chapter_4.pptx
 
Unit 4 chapter - 8 Transaction processing Concepts (1).pptx
Unit 4 chapter - 8 Transaction processing Concepts (1).pptxUnit 4 chapter - 8 Transaction processing Concepts (1).pptx
Unit 4 chapter - 8 Transaction processing Concepts (1).pptx
 
Database System Concepts AND architecture [Autosaved].pptx
Database System Concepts AND architecture [Autosaved].pptxDatabase System Concepts AND architecture [Autosaved].pptx
Database System Concepts AND architecture [Autosaved].pptx
 
Evolution Of WEB_students.pptx
Evolution Of WEB_students.pptxEvolution Of WEB_students.pptx
Evolution Of WEB_students.pptx
 
Presentation1.pptx
Presentation1.pptxPresentation1.pptx
Presentation1.pptx
 
Algorithm.pptx
Algorithm.pptxAlgorithm.pptx
Algorithm.pptx
 
Control_Statements_in_Python.pptx
Control_Statements_in_Python.pptxControl_Statements_in_Python.pptx
Control_Statements_in_Python.pptx
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
 
parts_of_python_programming_language.pptx
parts_of_python_programming_language.pptxparts_of_python_programming_language.pptx
parts_of_python_programming_language.pptx
 
linked_list.pptx
linked_list.pptxlinked_list.pptx
linked_list.pptx
 
matrices_and_loops.pptx
matrices_and_loops.pptxmatrices_and_loops.pptx
matrices_and_loops.pptx
 
algorithms_in_linkedlist.pptx
algorithms_in_linkedlist.pptxalgorithms_in_linkedlist.pptx
algorithms_in_linkedlist.pptx
 
Control_Statements.pptx
Control_Statements.pptxControl_Statements.pptx
Control_Statements.pptx
 

Recently uploaded

Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfstareducators107
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 
Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111GangaMaiya1
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of PlayPooky Knightsmith
 
What is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptxWhat is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptxCeline George
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningMarc Dusseiller Dusjagr
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsNbelano25
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfPondicherry University
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptNishitharanjan Rout
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSAnaAcapella
 
How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17Celine George
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
Introduction to TechSoup’s Digital Marketing Services and Use Cases
Introduction to TechSoup’s Digital Marketing  Services and Use CasesIntroduction to TechSoup’s Digital Marketing  Services and Use Cases
Introduction to TechSoup’s Digital Marketing Services and Use CasesTechSoup
 

Recently uploaded (20)

Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdf
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of Play
 
What is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptxWhat is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptx
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learning
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Introduction to TechSoup’s Digital Marketing Services and Use Cases
Introduction to TechSoup’s Digital Marketing  Services and Use CasesIntroduction to TechSoup’s Digital Marketing  Services and Use Cases
Introduction to TechSoup’s Digital Marketing Services and Use Cases
 

Object_Oriented_Programming_Unit3.pdf

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12. you must specify self explicitly when defining the method, you don’t include it when calling the method
  • 13.
  • 14.
  • 15. Classes are defined using keyword “Class” followed by user defined “ClassName” and a colon. Variables are also called attributes Functions are also called methods. Functions are also called methods. Syntax: class className: <statement-1> <statement-2> ; <statement-n>
  • 16.  class Mobile:  def __init__(self, name):  self.mobile_name=name  print("Constructor")  def receive_msg(self):  print(f"Receive Message from {self.mobile_name}")  def send_msg(self):  print(f"Send Message from {self.mobile_name}")  def main():  def main():  nokia = Mobile("Nokia")  nokia.receive_msg()  nokia.send_msg()  if __name__=="__main__":  main()  Output:  Constructor  Receive Message from Nokia  Send Message from Nokia •Class Mobile has 2 methods: -Receive_msg() - Send_msg() •Self has no meaning in Python. •It is used to improve readability. •__init__ function is called when an object is instantiated
  • 17.  Object refers to a particular instance of a class.  It contains variables and methods defined in the class.  Class objects support 2 kinds of operations. ◦ A. Attribute references – The names in class are referenced by objects and are called attribute references. There are two objects and are called attribute references. There are two kinds of attribute references.  A. Data attributes – Variables defined within methods are called instance variables / data attributes which are used to store data.  B. Method attributes – Functions that are inside a class and are referenced by objects of a class. B. Instantiation – Act of creating an object from a class.
  • 18.  class student:  def __init__(self,name,marks):  self.name = name  self.marks = marks  def check_pass_fail(self):  if self.marks >= 40:  return True  else:  return False •Student1 and Student2 are the objects of Student Class. •Student1 is instantiated with name as Harry and marks 30 •Student2 is instantiated with name as Jane and marks 99 •Whenever you call a method using an object,  def main():  student1 = student("Harry", 30)  student2 = student("Jane", 99)  did_pass = student1.check_pass_fail()  print(did_pass)  did_pass = student2.check_pass_fail()  print(did_pass)  if __name__=="__main__":  main() •Whenever you call a method using an object, the object is automatically passed in as the first parameter to the self parameter variable Output False True
  • 19.  class Birds:  def __init__(self, bird_name):  self.bird_name = bird_name  def flying_birds(self):  print(f"{self.bird_name} flies above clouds")  def non_flying_birds(self):  print(f"{self.bird_name} is the national bird of Australia")  def main():  vulture=Birds("Griffon Vulture")  Crane = Birds("Common Crane")  Emu = Birds("Emu")  vulture.flying_birds()  Crane.flying_birds()  Emu.non_flying_birds()  if __name__=="__main__":  main() Output: Griffon Vulture flies above clouds Common Crane flies above clouds Emu is the national bird of Australia vulture, Crane and Emu are the objects of class Birds
  • 20.  Only one constructor can be defined per class  Syntax:  def __init__(self,parameter_1,….parameter_n)  It defines and initializes the instance variables It is called as soon as an object of a class is  It is called as soon as an object of a class is instantiated.  All the data attributes of a class are initialised in the init function itself.
  • 21.  An object can be passed as an argument to a calling function  class Music:  def __init__(self,song,artist):  self.song=song  self.artist=artist def print_track_info(vocalist): Output: Song is Boy With Love Artist is BTS2  def print_track_info(vocalist):  print(f"Song is {vocalist.song}")  print(f"Artist is {vocalist.artist}")  singer = Music("Boy With Love","BTS")  print_track_info(singer)
  • 22.  class sum:  def __init__(self,num1,num2):  self.num1 = num1  self.num2 = num2  self.sum =" "  def add_sum(self):  self.sum = self.num1 + self.num2  return self Output: 9 1787802679712 True  return self  def main():  number =sum(4,5)  returned_object = number.add_sum()  print(returned_object.sum)  print(id(returned_object))  print(isinstance(returned_object,sum))  if __name__=="__main__":  main() •id(object) is a function that is used to find the identity of the location of the object in memory •Isinstance(object,classinfo) is a function that returns a boolean stating if the object is an instance of class or not.
  • 23.  class Dog:  kind ='Canine'  def __init__(self,name):  self.dog_name=name Class Attributes: Are Class variables that is shared by all objects of a class. Data Attributes Are instance variables unique to each object of a  d=Dog('Fido')  e=Dog("Buddy")  print(f"{d.kind}")  print(f"{e.kind}")  print(f"{d.dog_name}")  print(f"{e.dog_name}") Output: Canine Canine Fido Buddy unique to each object of a class.
  • 24.  Encapsulation -> Information hiding  Abstraction -> Implementation hiding  It is the process of combining variables that store data and methods that work on those variables into a single unit called class.  class foo:  def __init__(self,a,b):  self.a = a Output: 7  self.a = a  self.b = b  def add(self):  return self.a + self.b  foo_object =foo(3,4)  print(foo_object.add()) The internal representation of the foo class is hidden outside the class -> Encapsulation The implementation of add() function is hidden from the object. -> Abstraction
  • 25.  class Demo:  def __init__(self):  self.nonprivate="I am not a private instance"  self.__private="I am a private instance"  def display_privateinstance(self):  print(f"{self.__private} used within the method of a class") def main():  def main():  demo_obj = Demo()  demo_obj.display_privateinstance()  print(demo_obj.nonprivate)  # print(demo_obj.__private)  if __name__=="__main__":  main() Output: I am a private instance used within the method of a class I am not a private instance
  • 26.  The private instance variables cannot be accessed outside the class, but only through a method defined inside the class  In Python, an identifier with double underscore is treated as private.  Name mangling is intended to give the class an easy way to define private instance variables and methods  class Student:  def __init__(self, name):  self.__name = name // private attribute   s1 = Student("Santa")  print(s1._Student__name)  //Access using _class__private attribute
  • 27.  The class that is used as the basis for inheritance is called a superclass or base class.  A class that inherits from a base class is called a subclass or derived class.  The base class and derived class exhibit “is a” relationship in inheritance  Eg: Sitar is a stringed instrument  Eg: Sitar is a stringed instrument  Syntax of derived class:  Class DerivedClassName(BaseClassName):  <statement-1>  .  .  <statement-N>
  • 28.  It is possible to define the derived base when the base class is defined in another module.  Class DerivedClassName(modname.BaseClassName)  # module1.py  class Hello:  def show(self):  print("Module1.Hello.Show Welcome")  print("Module1.Hello.Show Welcome")  #modulederived.py  ______________________________________________________________________________________ import module1  class derived_module1(module1.Hello): # derived class of the Hello class in Module 1  def derived_class(self):  print("Hi")  def main():  check = derived_module1() # object of the derived_module1 class  check.show()  if __name__=="__main__":  main() Output: Module1.Hello.Show Welcome
  • 29.  class someclass(object): # this is derived out of the "class object"  def __init__(self):  print("Constructor")  def someclass_function(self):  print("Hello India") •All class except “Class object” are derived classes. •Class object is the base of inheritance hierarchy and hence has no derived classes.  def main():  obj = someclass()  obj.someclass_function()  if __name__=="__main__":  main() has no derived classes. •Classes without baseclassname are derived from the class object.
  • 30.  class cricket:  def __init__(self,IPLteam,owner,times_won):  self.IPLteam = IPLteam  self.owner = owner  self.times_won = times_won  def IPLOwner(self):  print(f"The IPL team {self.IPLteam} is owned by {self.owner}")  class derived_cricket(cricket):  class derived_cricket(cricket):  def IPLresults(self):  print(f"The IPL team {self.IPLteam} has won {self.times_won}")  def main():  cricket_fans=derived_cricket("KKR","SRK", 9)  cricket_fans.IPLOwner()  cricket_fans.IPLresults()  if __name__=="__main__":  main() Output: The IPL team KKR is owned by SRK The IPL team KKR has won 9
  • 31.  Derived_cricket is the derived class and cricket is the base class  Derived class inherits variables and methods of base class  __init__() method is also derived from base class. Derived  __init__() method is also derived from base class. Derived class has access of __init__() method of the base class.  The base class has 3 data attributes, IPLteam, owner and times_won. It has a method IPLOwner  Derived class has access to the data attributes and methods of the base class.
  • 32.  In Single Inheritance, built-in super() function is used to refer to base class without explicitly naming it.  If derived class has __init__() method and needs to access the base class __init__() method explicitly, then this is done using super().  If the derived class needs no attributes from base class, then we do not need to use super() method to invoke base class __init__() method. need to use super() method to invoke base class __init__() method.  Super().__init__(base_class_parameters)  Its usage is as below.  Class DerivedClass(BaseClass):  def__init__(self, derived_class_params, base_class_params)  super().__init__(base_class_params)  self.derived_class_params = derived_class_params
  • 33.  class country:  def __init__(self,country_name):  self.country_name = country_name  def country_details(self):  print(f"Happiest country in world is {self.country_name}")  class HappyCountry(country):  def __init__(self,country_name,continent):  super().__init__(country_name)  self.continent = continent  self.continent = continent  def Happy_Country_Details(self):  print(f"Happiest country in the world is {self.country_name} and it is in {self.continent}")  def main():  obj = HappyCountry("Finland","Europe")  obj.Happy_Country_Details()  if __name__=="__main__":  main() Output: Happiest country in the world is Finland and it is in Europe
  • 34.  The derived class __init__() method has its own parameters plus the base class parameters.  We do not need to specify self for base class init() method  Base class methods may be overridden (method overriding)  Derived class should have a method with same name as those in base class. Also signature (method name, order and total number of parameters) should be same.
  • 35. def main(): print("Derived Class") derived_obj=Friction("R K Narayan", "Malgudi Days", "India Book House") derived_obj.book_info() print("-----------------------") derived_obj.invoke_base_class_method() class Book:  def __init__(self,author,title):  self.author = author  self.title = title  def book_info(self):  print(f"{self.title} is authored by {self.author}") class Friction(Book): if __name__=="__main__": main() Output: Derived Class Malgudi Days is authored by R K Narayan and published by India Book House ----------------------- Malgudi Days is authored by R K Narayan class Friction(Book):  def __init__(self,author,title,publisher):  super().__init__(author,title)  self.publisher = publisher  def book_info(self):  print(f"{self.title} is authored by {self.author} and published by {self.publisher}")  def invoke_base_class_method(self):  super().book_info()
  • 36.  Python supports a form of multiple inheritances. A derived class definition with multiple base classes looks like  Class DerivedClassName(Base_1,Base_2, Base_3)  <statement_1>  .  .  <statement_N> The baseclass method can be invoked from the derived class using the  The baseclass method can be invoked from the derived class using the syntax  BaseClassName.methodname (self, arguments)  Issubclass(DerivedClassName, BaseClassName)  returns True if DerivedClassName is a derived class of base class BaseClassName.
  • 37.  class length:  l = 0  def length(self):  return self.l  class breadth:  b = 0  def breadth(self):  return self.b  class rect_area(length, breadth): # derived from class length and class breadth Output: Enter the required length for rectangle: 5 Enter the required breadth for rectangle: 4 The area of rectangle with length 5 units and breadth 4 units is 20 sq. units.  class rect_area(length, breadth): # derived from class length and class breadth  def r_area(self):  print("The area of rectangle with length "+str(self.l)+" units and breadth "+  str(self.b)+" units is "+str(self.l * self.b)+" sq. units.")  def main():  o = rect_area()  o.l = int(input("Enter the required length for rectangle: "))  o.b = int(input("Enter the required breadth for rectangle: "))  o.r_area()  if __name__=="__main__":  main()
  • 38.  class Pet:  def __init__(self,breed):  self.breed = breed  def about(self):  print(f"This is {self.breed} breed")  class Insurable:  def __init__(self,amount):  self.amount = amount def main(): dog_obj = dog(15, "Shitzu", 5000) dog_obj.about() dog_obj.get_weight() if __name__=="__main__": main()  self.amount = amount  def about(self):  print(f"It is insured for an amount {self.amount}")  class dog(Pet, Insurable):  def __init__(self,weight,breed,amount):  self.weight = weight  Pet.__init__(self,breed)  Insurable.__init__(self,amount)  def get_weight(self):  print(f" {self.breed} dog weights around {self.weight} pounds") Output: This is Shitzu breed Shitzu dog weights around 15 pounds [<class '__main__.dog'>, <class '__main__.Pet'>, <class '__main__.Insurable'>, <class 'object'>]
  • 39.  MRO denotes the way Python programming language resolves a method found in multiple base classes.  Syntax : class_name.mro()  Syntax : class_name.mro()  It uses C3 linearization algorithm to determine the order of the methods to be invoked in multiple inheritances
  • 40.  class First:  def my_method(self):  print("You found me in class first")  class Second:  def my_method(self):  print("you found me in class second")  class Third:  def my_method(self): def main(): obj = Sixth() obj.my_method() print(Sixth.mro()) if __name__=="__main__": main()  print("you found me in class Third")  class Fourth(Third,First):  pass  class Fifth(Third, Second):  pass  class Sixth(Fifth, Fourth):  pass Output: you found me in class Third [<class '__main__.Sixth'>, <class '__main__.Fifth'>, <class '__main__.Fourth'>, <class '__main__.Third'>, <class '__main__.Second'>, <class '__main__.First'>, <class 'object'>]
  • 41.  class First:  def __init__(self):  print("In First")  super().__init__()  class Second:  def __init__(self):  print("In Second")  super().__init__() Output: In Third In First In Second Method Resolution order is [<class '__main__.Third'>, <class '__main__.First'>, <class '__main__.Second'>, <class 'object'>]  class Third (First,Second):  def __init__(self):  print("In Third")  super().__init__()  def main():  obj = Third()  print(f"Method Resolution order is {Third.mro()}")  if __name__=="__main__":  main() First the __init__() method of class Third is called. This prints “In Third”. After this super().__init__() is called which in turn calls the __init__() method of the next class found in MRO.
  • 42.  import math  pi = 3.141  class square:  def __init__(self, length):  self.l = length  def perimeter(self):  return 4 * (self.l)  def area(self):  return self.l * self.l  class Circle:  def __init__(self, radius): •Square and Circle are the derived classes •The derived classes have the methods perimeter() and area() which are common to both •But the implementation of these two methods is different in each of the 2 classes.  def __init__(self, radius):  self.r = radius  def perimeter(self):  return 2 * pi * self.r  def area(self):  return pi * self.r ** 2  # Initialize the classes  sqr = square(10)  c1 = Circle(4)  print("Perimeter computed for square: ", sqr.perimeter())  print("Area computed for square: ", sqr.area())  print("Perimeter computed for Circle: ", c1.perimeter())  print("Area computed for Circle: ", c1.area()) Output: Perimeter computed for square: 40 Area computed for square: 100 Perimeter computed for Circle: 25.128 Area computed for Circle: 50.256
  • 43.  This is a specific case of Polymorphism.  “Poly” means many and “morphism” means forms. You can have multiple classes where each class implements the same variables or methods in different ways. methods in different ways.  Operator overloading is a specific case of polymorphism, where an operator can have different meaning when used with operands of different types.
  • 44.
  • 45.
  • 46.  class Rectangle:  def __init__(self,width,height):  self.width = width  self.height = height  def __gt__(self,other):  rectangle_l_area = self.width * self.height  rectangle_2_area = other.width * other.height  return rectangle_l_area > rectangle_2_area Output: rectangle 1 is greater than rectangle 2  def main():  rectangle_1_obj = Rectangle(5,10)  rectangle_2_obj = Rectangle(3,4)  if rectangle_1_obj > rectangle_2_obj:  print("rectangle 1 is greater than rectangle 2")  else:  print("rectangle 2 is greater than rectangle 1")  if __name__=="__main__":  main() •rectangle_1_obj and rectangle_2_obj are objects of the Rectangle class. •When the expression rectangle_l_area > rectangle_2_area is evaluated, then the method rectangle_1_obj.__gt__(rectangle_2_obj) gets invoked.
  • 47.  class Complex:  def __init__(self,real,imaginary):  self.real = real  self.imaginary = imaginary  def __add__(self,other):  return Complex (self.real + other.real, self.imaginary + other.imaginary)  def __str__(self):  return f"{self.real} + i{self.imaginary}"  return f"{self.real} + i{self.imaginary}"  def main():  complex_number_1 = Complex(4,5)  complex_number_2 = Complex(2,3)  complex_number_sum = complex_number_1 + complex_number_2  print(f"{complex_number_1} + {complex_number_2} = {complex_number_sum}")  if __name__=="__main__":  main()
  • 48.  complex_number_sum = complex_number_1 + complex_number_2 will execute as  Complex_number_1.__add__(complex_number_2)  __add__() method is called magic method.  Whenever we have to print the complex_number formatted,  Whenever we have to print the complex_number formatted, then __str__() magic method is called which is implemented as shown in the program  The __str__() method returns the values of real and imaginary data concatenated together and imaginary part is prefixed with i.