0% found this document useful (0 votes)
21 views35 pages

Chapter 5

Uploaded by

vidyadevi6996
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)
21 views35 pages

Chapter 5

Uploaded by

vidyadevi6996
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/ 35

Object Oriented

Programming in python
Classes And Objects in Python
Class:
Python is an object oriented programming
language.
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.
To create a class, use the keyword class:
class MyClass:
x=5
Object:
We can use the class named MyClass to create
objects:
p1 = MyClass()
print(p1.x)
The __init__() Function:
Classes and objects in their simplest form are
not really useful in real life applications.
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:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)

The __init__() function is called automatically


every time the class is being used to create a
new object.
Object Methods
Objects can also contain methods. Methods in
objects are functions that belong to the 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()
The self Parameter
 The self parameter is a reference to the current instance of the
class, and is used to access variables that belongs 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:
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()
You can modify properties on objects like this:
p1.age = 40
You can delete properties on objects by using
the del keyword:
del p1.age
You can delete objects by using the del
keyword:
del p1
Method Overloading
Python does not support method overloading
by default. But there are different ways to
achieve method overloading in Python.
The problem with method overloading in
Python is that we may overload the methods
but can only use the latest defined method.
We may define many methods of the same
name and different arguments, but we can
only use the latest defined method. Calling
the other method will produce an error.
def product(a, b):
p=a*b
print(p)

# Second product method


# Takes three argument and print their product
def product(a, b, c):
p = a * b*c
print(p)

# Uncommenting the below line shows an error


# product(4, 5)

# This line will call the second product method


product(4, 5, 5)
Not The Most Efficient Method
We can use the arguments to make the same function work differently i.e.
as per the arguments.

def add(datatype, *args):

if datatype =='int':
answer = 0

if datatype =='str':
answer =''

# Traverse through the arguments


for x in args:

answer = answer + x

print(answer)

add('int', 5, 6)

add('str', ‘Bharati', ‘Vidyapeeth')


By Using
Multiple Multiple
Dispatch Dispatch
Decorator Decorator
Can be installed
by:
pip3 install multipledispatch

from multipledispatch import dispatch

#passing one parameter


@dispatch(int,int)
def product(first,second):
result = first*second
print(result);

@dispatch(float,float,float)
def product(first,second,third):
result = first * second * third
print(result);

product(2,3,2) #this will give output of 12


product(2.2,3.4,2.3) # this will give output of
17.985999999999997
Advantages of Method Overloading in
Python:
Normally methods are used to reduce complexity.
Method overloading is even it reduce more
complexity in the program also improves the
clarity of code.
It is also used for reusability.

Disadvantages:
When creating more confusion during the
inheritance concepts.
In python, we create a single method with
different arguments to process the Method
Overloading. Here we create a method with zero
or more parameters and also define the methods
based on the number of parameters.
class Area:
def find_area(self,a=None,b=None):
if a!=None and b!=None:
print("Area of Rectangle:",(a*b))
elif a!=None:
print("Area of square:",(a*a))
else:
print("Nothing to find")
obj1=Area()
obj1.find_area()
obj1.find_area(10)
obj1.find_area(10,20)
Method Overriding
 Method overriding is a concept of object oriented
programming that allows us to change the implementation of a
function in the child class that is defined in the parent class. It is
the ability of a child class to change the implementation of any
method which is already provided by one of its parent
class(ancestors).
Following conditions must be met for overriding a function:
 Inheritance should be there. Function overriding cannot be done

within a class. We need to derive a child class from a parent


class.
 The function that is redefined in the child class should have the

same signature as in the parent class i.e. same number of


parameters.
class Animal:
multicellular = True
eukaryotic = True

# function breath
def breathe(self):
print("I breathe oxygen.")

# function feed
def feed(self):
print("I eat food.")

# child class
class Herbivorous(Animal):

# function feed
def feed(self):
print("I eat only plants. I am vegetarian.")

herbi = Herbivorous()
herbi.feed()
herbi.breathe()
Data Hiding
 Data hiding is a part of object-oriented programming,
which is generally used to hide the data information
from the user. It includes internal object details such as
data members, internal working.
 It maintained the data integrity and restricted access
to the class member. The main working of data hiding
is that it combines the data and functions into a single
unit to conceal data within a class.
 We cannot directly access the data from outside the
class.
 This process is also known as the data
encapsulation. It is done by hiding the working
information to user.
 In the process, we declare class members as private so
that no other class can access these data members. It is
accessible only within the class.
In the Python programming, Data hiding
isolates the client from a part of program
implementation. Some of the essential
members must be hidden from the user.
Programs or modules only reflected how we
could use them, but users cannot be familiar
with how the application works. Thus it
provides security and avoiding dependency as
well.
We can perform data hiding in Python using
the __ double underscore before prefix. This
makes the class members private and
inaccessible to the other classes.
class CounterClass:
__privateCount = 0
def count(self):
self.__privateCount += 1
print(self.__privateCount)
counter = CounterClass()
counter.count()
counter.count()
print(counter.__privateCount)

However we can access the private member


using the class name.
print(counter.CounterClass__privatecounter)
Advantages of Data Hiding
The class objects are disconnected from the
irrelevant data.
It enhances the security against hackers that
are unable to access important data.
It isolates object as the basic concept of OOP.
It helps programmer from incorrect linking to
the corrupt data.
We can isolate the object from the basic
concept of OOP.
It provides the high security which stops
damage to violate data by hiding it from the
public.
Disadvantages of Data Hiding
Sometimes programmers need to write the
extra lien of the code.
The data hiding prevents linkage that act as
link between visible and invisible data makes
the object faster.
It forces the programmers to write extra code
to hide the important data from the common
users.
Data Abstraction
Abstraction is used to hide the internal
functionality of the function from the users.
The users only interact with the basic
implementation of the function, but inner
working is hidden. User is familiar with
that "what function does" but they don't
know "how it does.“
In Python, an abstraction is used to hide the
irrelevant data/class in order to reduce the
complexity. It also enhances the application
efficiency. Next, we will learn how we can
achieve abstraction using the Python
program.
In Python, abstraction can be achieved by using
abstract classes and interfaces.
A class that consists of one or more abstract
method is called the abstract class. Abstract
methods do not contain their implementation.
Abstract class can be inherited by the subclass
and abstract method gets its definition in the
subclass.
Abstraction classes are meant to be the
blueprint of the other class. An abstract class
can be useful when we are designing large
functions.
An abstract class is also helpful to provide the
standard interface for different implementations
of components. Python provides the abc module
to use the abstraction in the Python program.
from abc import ABC
class ClassName(ABC):

from abc import ABC, abstractmethod


class Car(ABC):
def mileage(self):
pass

class Tesla(Car):
def mileage(self):
print("The mileage is 30kmph")
class Suzuki(Car):
def mileage(self):
print("The mileage is 25kmph ")
class Duster(Car):
def mileage(self):
print("The mileage is 24kmph ")

class Renault(Car):
def mileage(self):
print("The mileage is 27kmph ")
# Driver code
t= Tesla ()
t.mileage()

r = Renault()
r.mileage()

s = Suzuki()
s.mileage()
d = Duster()
d.mileage()

•An Abstract class can contain the both method normal and
abstract method.
•An Abstract cannot be instantiated; we cannot create objects
for the abstract class.
Inheritance and Composition
It is a concept of Object-
Oriented Programming. Inheritance is a
mechanism that allows us to inherit all the
properties from another class.
The class from which the properties and
functionalities are utilized is called
the parent class (also called as Base Class).
The class which uses the properties from
another class is called as Child Class (also
known as Derived class).
Inheritance is also called an Is-A Relation.
In the given figure, classes are
represented as boxes. The inheritance
relationship is represented by an arrow
pointing from Derived Class(Child
Class) to Base Class(Parent Class).
The extends keyword denotes that
the Child Class is inherited or derived
from Parent Class.
# Parent class
class Parent :
# Constructor
# Variables of Parent class

# Methods
...

...

# Child class inheriting Parent class


class Child(Parent) :
# constructor of child class
# variables of child class
# methods of child class

...

...
# parent class
class Parent:
# parent class method
def m1(self):
print('Parent Class Method called...')

# child class inheriting parent class


class Child(Parent):

# child class constructor


def __init__(self):
print('Child Class object created...')

# child class method


def m2(self):
print('Child Class Method called...')

# creating object of child class


obj = Child()

# calling parent class m1() method


obj.m1()
# calling child class m2() method
obj.m2()
Composition Classes
Composition is one of the fundamental
concepts of Object-Oriented Programming.
References to one or more objects of other
classes as an Instance variable.
By using the class name or by creating the
object we can access the members of one
class inside another class.
It enables creating complex types by
combining objects of different classes. It
means that a class Composite can contain an
object of another class Component.
This type of relationship is known as Has-A
Relation.
 In the figure Classes are represented as
boxes with the class.
 Name Composite and Component represen
ting Has-A relation between both of them.
 Syntax:
class A :
# variables of class A
# methods of class A
... ...
class B :
# by using "obj" we can access member's of
class A.
obj = A()
# variables of class B
# methods of class B
... ...
class Component:
# composite class constructor
def __init__(self):
print('Component class object created...')
# composite class instance method
def m1(self):
print('Component class m1() method executed...')
class Composite:
# composite class constructor
def __init__(self):
# creating object of component class
self.obj1 = Component()
print('Composite class object also created...')
# composite class instance method
def m2(self):
print('Composite class m2() method executed...')
# calling m1() method of component class
self.obj1.m1()
# creating object of composite class
obj2 = Composite()
# calling m2() method of composite class
obj2.m2()
Customization via Inheritance
specializing inherited methods:
The tree-searching model of inheritance turns
out to be a great way to specialize systems.
Because inheritance finds names in
subclasses before it checks superclasses,
subclasses can replace default behavior by
redefining the superclass's attributes.
In fact, you can build entire systems as
hierarchies of classes, which are extended by
adding new external subclasses rather than
changing existing logic in place.
The idea of redefining inherited names leads
to a variety of specialization techniques.
 For instance, subclasses may replace inherited
attributes completely, provide attributes that a
superclass expects to find, and extend superclass
methods by calling back to the superclass from an
overridden method.
 Extension is the only way to interface with a
superclass.
 Super: Defines a method function and a delegate
that expects an action in a subclass.
 Inheritor: Doesn't provide any new names, so it gets
everything defined in Super.
 Replacer: Overrides Super's method with a version
of its own.
 Extender: Customizes Super's method by overriding
and calling back to run the default.
 Provider: Implements the action method expected by
Super's delegate method.
Example- For specialized inherited methods.
class A:
"parent class" #parent class
def display(self):
print("This is base class")
class B(A):
"Child class" #derived class
def display(self):
A.display(self)
print("This is derived class")
obj=B()
#instance of child
obj.display()
#child calls overridden method
class super:
def method(self):
print("in super.method") #default behavior
def delegate(self):
self.action() #expected to be defined
class inheritor(super):
pass
class replacer(super): #replace method completely
def method(self):
print("in replacer.method")
class extender(super): #extend method behavior
def method(self):
super.method(self)
print("in extender.method")
class provider(super): # fill in a required method
def action(self):
print("in provider.action")
for klass in (inheritor,replacer,extender):
print("\n"+klass.__name__+"...")
klass().method()
print("\n provider...")
x=provider()
x.delegate()

You might also like