0% found this document useful (0 votes)
14 views

OOP UNIT 4 Inheritance 1

Uploaded by

naikpoojitha33
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

OOP UNIT 4 Inheritance 1

Uploaded by

naikpoojitha33
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 41

OBJECT ORIENTED PROGRAMMING

(23EN1202)

UNIT-4: INHERITANCE IN PYTHON

2/22/2024 1.0001 LECTURE 1


Syllabus
Introduction
Inheritance is one of the powerful features of Object oriented
programming. It allows us to define/create a class by inheriting all the
methods and properties from another(Parent) class.

Parent class is the class being inherited from, also called base class.

Child class is the class that inherits from another class, also called
derived class.

2/22/2024 1.0001 LECTURE 1


Python Inheritance Syntax
class BaseClass:
Body of base class

class DerivedClass(BaseClass):
Body of derived class

Derived class inherits features from the base class, adding new features
to it. This results into re-usability of code.

2/22/2024 1.0001 LECTURE 1


Inheritance
Inheritance Models “is a” Relationship
⮚Inheritance follows a top-down approach to problem solving.

⮚In top-down approach , generalized(base) classes are designed


first and then specialized classes are derived by
inheriting/extending the generalized(base) classes.

⮚Fig 1.1 Illustrates the concept of top-down approach in


Inheritance.
Inheritance Models “is a” Relationship
Fig: 1.1
Example Code:
class university:
def __init__(self, name):
self.name1 = name
def display(self):
print("welcome to ",self.name1)
class program(university):
def __init__(self, name, p1,p2):
university. __init__(self, name)
self.pr1=p1
self.pr2=p2
def display(self):
university.display(self)
print(f"{self.name1} has {self.pr1} and {self.pr2}")
obj=program("DSU","SOE","SOL")
obj.display()
POLYMORPHISM
⮚Polymorphism , in simple terms, refers to having several diffrent
forms.
⮚It is one of the key features of OOPP.
⮚Polymorphism is the ability of different objects to respond to the
same message (method call) in different ways.
⮚In the context of object-oriented programming, this often means
that different classes can define the same method name but with
different implementations.
Polymorphism
Polymorphism
⮚In our example, imagine a picture of a person. This person can
transform into various roles: a student, an employee, a customer,
a family member, and a husband. Each role represents a different
behavior or function of the person.
⮚Polymorphism simplifies code structure and promotes reusability
by allowing objects to exhibit different behaviors while
maintaining a common interface.
class Person:

def role(self):

return "Generic person”

class Employee(Person):

def role(self):

return "Employee: Works diligently"

class Customer(Person):

def role(self):

return "Customer: Shops for goods"

class FamilyMember(Person):

def role(self):

return "Family Member: Spends time with family"

def display_role(person):

return person.role()

employee = Employee()

customer = Customer()

family_member = FamilyMember()

print(display_role(employee)) # Output: Works diliegently

print(display_role(customer)) # Output: Customer: Shops for goods

print(display_role(family_member)) # Output: Family Member: Spends time with family


Method overriding
⮚Method overriding is the ability of a class to change the
implementation of a method provided by one of its ancestors.
⮚It is an important concept of OOPP since it exploits the power of
inheritance and polymorphism.
⮚It allows the subclass to provide a specialized version of the
method that is tailored to its own behavior while still
maintaining the same method signature as the superclass.
EXAMPLE:
class Person:
def greet(self):
return "Hello, I am a person."
class Student(Person):
def greet(self):
return "Hi, I am a student."
class Teacher(Person):
def greet(self):
return "Hello, I am a teacher."
student = Student()
teacher = Teacher()
print(student.greet()) # Output: Hi, I am a student.
print(teacher.greet()) # output: Hi, I am a Teacher
Built-in-functions
isinstance() and issubclass() are two built-in functions in Python used
for checking object types and class relationships, respectively.
⮚ isinstance(): Determines if an object is an instance of a class or a
subclass of a class.
⮚ syntax: isinstance(object, classinfo)
object: The object to be checked.
classinfo: A class, type, or tuple of classes and types to check
against.
⮚ Returns True if the object is an instance of the specified class or

any of its subclasses.False otherwise.


Example:
class Dog:
pass

dog = Dog()
print(isinstance(dog, Dog)) # Output: True
print(isinstance(dog, object)) # Output: True (all objects are
instances of the base object class)
issubclass()
⮚ Determines if a class is a subclass of another class.

⮚ Syntax: issubclass(class, classinfo)


class: The class to be checked.
classinfo: A class, type, or tuple of classes and types to check
against.

⮚ Returns True if the class is a subclass of the specified class or any of its
subclasses. False otherwise.
Example:
class Animal:
pass

class Dog(Animal):
pass

print(issubclass(Dog, Animal)) # Output: True


print(issubclass(Dog, object)) # Output: True (all classes are subclasses of the base object
class)
Example:
class Animal:
pass

class Dog(Animal):
pass

print(issubclass(Dog, Animal)) # Output: True


print(issubclass(Dog, object)) # Output: True (all classes are subclasses
of the base object class)
Super() Function

⮚super() function is used to access methods and properties from a


parent class within a subclass.

⮚It provides a way to call methods of the superclass without


explicitly naming them, which can be particularly useful in cases
of inheritance and method overriding.
Calling the Parent Class Constructor:
⮚ One common use of super() is to call the constructor of the parent class within the constructor of a
subclass.
⮚ This allows you to initialize the inherited attributes along with any additional attributes specific to the
subclass.
class Parent:
def __init__(self, name):
self.name = name

class Child(Parent):
def __init__(self, name, age):
super().__init__(name) # Call the constructor of the Parent class
self.age = age

child = Child("Abc”, 10)


print(child.name) # Output: Abc
print(child.age) # Output: 10
Accessing Parent Class Methods:

You can also use super() to access methods of the parent class from within the
subclass.

This is particularly useful when you want to extend or modify the behavior of
the parent class method in the subclass.
class Parent:
def greet(self):
return "Hello from Parent"

class Child(Parent):
def greet(self):
return super().greet() + ", and Hello from Child"

child = Child()
print(child.greet()) # Output: Hello from Parent, and Hello from Child
Types of Inheritance
1. Single Inheritance
2. Multiple Inheritance
3. Multi-level Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
Single Inheritance
⮚In single inheritance, a subclass inherits from only one
superclass.
⮚This is the simplest form of inheritance.
Example:
class Animal:
def __init__(self, species):
self.species = species

class Mammal(Animal):
def __init__(self, species, has_hair):
super().__init__(species)
self.has_hair = has_hair

dog = Mammal("Dog", True)


cat = Mammal("Cat", True)

print(dog.species, dog.has_hair) # Output: Dog True


print(cat.species, cat.has_hair) # Output: Cat True
Multiple Inheritance
⮚ In multiple inheritance, a subclass inherits from more than one superclass.
⮚ This allows the subclass to access attributes and methods from multiple
parent classes.
Example:
class CommunicationDevice:
def make_call(self):
print("Making a call...")

class MultimediaDevice:
def play_video(self):
print("Playing a video...")

class Smartphone(CommunicationDevice, MultimediaDevice):


pass

smartphone = Smartphone()
smartphone.make_call() # Output: Making a call...
smartphone.play_video() # Output: Playing a video...
Multi-level Inheritance
⮚ In multilevel inheritance, a subclass inherits from another subclass,
forming a chain of inheritance.
⮚ This creates a hierarchy of classes where each class inherits from the
class above it.
Example:
class Intern:
def __init__(self, name):
self.name = name

class RegularEmployee(Intern):
def __init__(self, name, department):
super().__init__(name)
self.department = department

class Manager(RegularEmployee):
def __init__(self, name, department, team):
super().__init__(name, department)
self.team = team

manager = Manager("John", "Engineering", "Development")


print(manager.name, manager.department, manager.team) # Output: John Engineering Development
Exercise
1. Create a program that demonstrates polymorphism in Python by modeling different types
of birds, each with unique sounds.
2. Design and implement a Python program to demonstrate the different types of inheritance
supported in object-oriented programming.
Python Classes and Objects
Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor, or a "blueprint" for creating objects.Create
a Class
To create a class, use the keyword class:
Example
Create a class named MyClass, with a property named x:
class MyClass:
x=5
Create Object
Now we can use the class named MyClass to create objects:

Example
Create an object named p1, and print the value of x:
p1 = MyClass()
print(p1.x)
The __init__() Function
The examples above are classes and objects in their simplest form,
in real life applications.
To understand the meaning of classes we have to understand the
built-in __init__() function.
All classes have a function called __init__(), which is always
executed when the class is being initiated.
Use the __init__() function to assign values to object properties, or
other operations that are necessary to do when the object is being
created:
Example
Create a class named Person, use the __init__() function to assign values for name and age:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Output: John
36
The __str__() function controls what should be returned when the class
object is represented as a string.

Example: The string representation of an object WITHOUT the __str__() function:


class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1)
<__main__.Person object at 0x0000023C820F3410> You probably meant to print the return value of the
method, for which you have to call it:
Example: The string representation of an object WITH the
__str__() function:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}({self.age})"
p1 = Person("John", 36)
print(p1)
Output : John(36)
Object Methods
Objects can also contain methods. Methods in objects are functions that
belong to the object.
Example: Insert a function that prints a greeting, and execute it on the p1
object:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc() Output : Hello my name is John
The self parameter is a reference to the current instance of the class, and is used to access
variables that belong to the class.
It does not have to be named self, you can call it whatever you like, but it has to be the first
parameter of any function in the class:
Example Use the words mysillyobject and abc instead of self:
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc() Output : John(36)
Modify Object Properties
Example :Set the age of p1 to 40:
p1.age = 40
Delete Object Properties You can delete properties on objects by using the del
keyword:
Example Delete the age property from the p1 object:
del p1.age
Delete Objects You can delete objects by using the del keyword:
Example :Delete the p1 object:
del p1
The pass Statement
class definitions cannot be empty, but if you for some reason have a class definition
with no content, put in the pass statement to avoid getting an error.

Example
class Person:
pass
THANK YOU

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy