[go: up one dir, main page]

0% found this document useful (0 votes)
30 views47 pages

Unit 5

The document provides an overview of Object Oriented Programming (OOP) concepts in Python, including classes, objects, inheritance, polymorphism, encapsulation, and data abstraction. It explains the syntax for creating classes, the role of constructors and destructors, and the differences between OOP and procedural programming. Additionally, it covers method overloading and various types of inheritance, illustrating these concepts with code examples.

Uploaded by

shekharvatmode
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)
30 views47 pages

Unit 5

The document provides an overview of Object Oriented Programming (OOP) concepts in Python, including classes, objects, inheritance, polymorphism, encapsulation, and data abstraction. It explains the syntax for creating classes, the role of constructors and destructors, and the differences between OOP and procedural programming. Additionally, it covers method overloading and various types of inheritance, illustrating these concepts with code examples.

Uploaded by

shekharvatmode
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/ 47

Unit - 05

Object Oriented Programming


in Python
Object Oriented Concepts

• Python is an object-oriented programming language. It


allows us to develop applications using an Object Oriented
approach. In Python, we can easily create and use classes
and objects.
• Major principles of object-oriented programming system

1) Object
2) Class
3) Method
4) Inheritance
5) Polymorphism
6) Data Abstraction
7) Encapsulation
• What are classes and objects in Python?
• Python is an object oriented programming language. Unlike
procedure oriented programming, where the main
emphasis is on functions, object oriented programming
stress on objects.
• Object is simply a collection of data (variables) and
methods (functions) that act on those data. And, class is a
blueprint for the object.
• We can think of class as a sketch (prototype) of a house. It
contains all the details about the floors, doors, windows
etc. Based on these descriptions we build the house. House
is the object.
• As, many houses can be made from a description, we can
create many objects from a class. An object is also called an
instance of a class and the process of creating this object is
called as instantiation
Syntax for creating a Class

To create a class use “class” keyword


class ClassName:
#statement_suite
Ex:
class MyClass:
x=5
print(MyClass.x)
• Defining a Class in Python
• Like function definitions begin with the keyword def
, in Python, we define a class using the keyword
class.

• The first string is called docstring and has a brief


description about the class. Although not
mandatory, this is recommended.

• Here is a simple class definition.


class MyNewClass:
‘’’This is a docstring. I have created a new class’’’
pass
• A class creates a new local namespace where
all its attributes are defined. Attributes may be
data or functions.

• There are also special attributes in it that


begins with double underscores (__). For
example, __doc__ gives us the docstring of
that class.
class MyClass:
'''This is my second class'''
a = 10
def func(self):
print('Hello')

Obj=MyClass()
print(Obj.a)

Obj.func()

print(Obj.__doc__)
• self represents the instance of the class. By using the “self”
keyword we can access the attributes and methods of the
class in python. It binds the attributes with the given
arguments.

• Python decided to do methods in a way that makes the


instance to which the method belongs be passed
automatically, but not received automatically: the first
parameter of methods is the instance the method is called
on

• Self is a convention and not a real python keyword


self is parameter in function and user can use another
parameter name in place of it. But it is advisable to use self
because it increase the readability of code.
Inheritance
• Inheritance is the most important aspect of object-oriented
programming which simulates the real world concept of
inheritance. It specifies that the child object acquires all the
properties and behaviors of the parent object.

• Example : Father-child , Shape-triangle,square

• By using inheritance, we can create a class which uses all the


properties and behavior of another class. The new class is known
as a derived class or child class, and the one whose properties are
acquired is known as a base class or parent class.

• It provides re-usability of the code.


Polymorphism
• Polymorphism contains two words "poly" and "morphs".
Poly means many and Morphs means form, shape.
• By polymorphism, we understand that one task can be
performed in different ways.
• For example You have a class animal, and all animals
speak. But they speak differently. Here, the "speak"
behavior is polymorphic in the sense and depends on the
animal. So, the abstract "animal" concept does not
actually "speak", but specific animals (like dogs and
cats) have a concrete implementation of the action
"speak".
Encapsulation

• Encapsulation is also an important aspect of


object-oriented programming. It is used to
restrict access to methods and variables. In
encapsulation, code and data are wrapped
together within a single unit from being
modified by accident.
• Example : class is the encapsulation of
variables and methods , different departments
of company
Data Abstraction

• Data abstraction and encapsulation both are often


used as synonyms. Both are nearly synonym
because data abstraction is achieved through
encapsulation.
• Abstraction is used to hide internal details and
show only functionalities. Abstracting something
means to give names to things so that the name
captures the core of what a function or a whole
program does.
• Example : ATM machine , Door Lock etc.
Index Object-oriented Procedural Programming
Programming
1. Object-oriented programming is Procedural programming uses a list
the problem-solving approach of instructions to do computation
and used where computation is step by step.
done by using objects.

2. It makes the development and In procedural programming, It is not


maintenance easier. easy to maintain the codes when the
project becomes lengthy.

3. It simulates the real world entity. It doesn't simulate the real world. It
So real-world problems can be works on step by step instructions
easily solved through oops. divided into small parts called
functions.

4. It provides data hiding. So it is Procedural language doesn't provide


more secure than procedural any proper way for data binding, so
languages. You cannot access it is less secure.
private data from anywhere.

5. Example of object-oriented Example of procedural languages


programming languages is C++, are: C, Fortran, Pascal, VB etc.
Java, .Net, Python, C#, etc.
• The __init__ method is similar to constructors in C++ and Java.
Constructors are used to initialize the object’s state. The task of
constructors is to initialize(assign values) to the data members of the
class when an object of class is created. Like methods, a constructor also
contains collection of statements(i.e. instructions) that are executed at
time of Object creation. It is run as soon as an object of a class is
instantiated. The method is useful to do any initialization you want to do
with your object.

# A Sample class with init method


class Person:

# init method or constructor


def __init__(self, name):
self.name = name

# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)

p = Person('Nikhil')
p.say_hi()
# A Sample class with init method
class Person:

# init method or constructor


def __init__(self, name):
self.name = name

# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)

# Creating different objects


p1 = Person('Nikhil')
p2 = Person('Abhinav')
p3 = Person('Anshul')

p1.say_hi()
p2.say_hi()
p3.say_hi()
• class car:

• # init method or constructor
• def __init__(self, model, color):
• self.model = model
• self.color = color

• def show(self):
• print("Model is", self.model )
• print("color is", self.color )

• # both objects have different self which
• # contain their attributes
• audi = car("audi a4", "blue")
• ferrari = car("ferrari 488", "green")

• audi.show() # same output as car.show(audi)
• ferrari.show() # same output as car.show(ferrari)

• # Behind the scene, in every instance method
• # call, python sends the instances also with
• # that method call like car.show(audi)
Python Constructor

• A constructor is a special type of method (function) which is used


to initialize the instance members of the class.
• Constructors can be of two types.
 Default Constructor
 Parameterized Constructor

1. default constructor – this is the one, which we have seen in the


above example. This constructor doesn’t accept any arguments.

2. parameterized constructor – constructor with parameters is


known as parameterized constructor.
Example demonstrating default constructor

class Student:
# Constructor - non parameterized
def __init__(self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello",name)
student = Student()
student.show("John")
• Example demonstrating parameterized
constructor :

class Employee:
def __init__(self,name,id):
self.id=id;
self.name=name;
def display(self):
print("ID: %d \nName: %s"%(self.id,self.name))

emp1 = Employee("Ravi",1)
emp2 = Employee("Amol",2)

emp1.display()
emp2.display()
Python destructor
• Destructors are called when an object gets destroyed. In
Python, destructors are not needed as much needed in C++
because Python has a garbage collector that handles memory
management automatically.
• The __del__() method is a known as a destructor method in
Python. It is called when all references to the object have been
deleted i.e when an object is garbage collected.

• Syntax of destructor declaration :

def __del__(self):
# body of destructor
# Python program to illustrate destructor
class Employee:

# Initializing
def __init__(self):
print('Employee created.')

# Deleting (Calling destructor)


def __del__(self):
print('Destructor called, Employee deleted.')

obj = Employee()
del obj
Python In-built class functions
S.r Function Description
1 getattr(obj,name,default) It is used to access the attribute
of the object.

2 setattr(obj, name,value) It is used to set a particular value


to the specific attribute of an
object.

3 delattr(obj, name) It is used to delete a specific


attribute.
4 hasattr(obj, name) It returns true if the object
contains some specific attribute.
class Student:
def __init__(self,name,id,age):
self.name = name;
self.id = id;
self.age = age

#creates the object of the class Student


s = Student("John",101,22)

#prints the attribute name of the object s


print(getattr(s,'name'))

# reset the value of attribute age to 23


setattr(s,"age",23)

# prints the modified value of age


print(getattr(s,'age'))

# prints true if the student contains the attribute with name id

print(hasattr(s,'id'))
# deletes the attribute age
delattr(s,'age')

# this will give an error since the attribute age has been deleted
Built-in class attributes

SN Attribute Description
1 __dict__ It provides the dictionary containing
the information about the class
namespace.

2 __doc__ It contains a string which has the class


documentation

3 __name__ It is used to access the class name.

4 __module__ It is used to access the module in


which, this class is defined.

5 __bases__ It contains a tuple including all base


classes.
Example:
class Student:
def __init__(self,name,id,age):
self.name = name;
self.id = id;
self.age = age
def display_details(self):
print("ID: {} \nName: {} \nAge:{}".format(self.name,self.id,self.age))

s = Student("John",101,22)
print(s.__doc__)
print(s.__dict__)
print(s.__module__)
Method Overloading
Like other languages (for example method overloading in C++) do,
python does not supports method overloading. We may overload the
methods but can only use the latest defined method.

Example :

def product(a, b):


p=a*b
print(p)

def product(a, b, c):


p=a*b*c
print(p)

product(4, 5)

product(4, 5, 5)
• Method overloading in python

• In Python, you can create a method that can be


called in different ways. So, you can have a method
that has zero, one or more number of parameters.
Depending on the method definition, we can call it
with zero, one or more arguments.

• Given a single method or function, the number of


parameters can be specified by you. This process of
calling the same method in different ways is called
method overloading.
class Person:

def sayHello(self, name=None):

if name is not None:


print('Hello ' + name)
else:
print('Hello ')

obj = Person()

obj.sayHello()

obj.sayHello(‘VVP')
def add(datatype, *args):

if datatype =='int':
answer = 0

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

for x in args:
answer = answer + x

print(answer)

add('str',"vvp"," polytechnic"," soregaon"," solapur")


add('int',10,20)
Inheritance
• Inheritance provides code reusability to the program because
we can use an existing class to create a new class instead of
creating it from scratch.
• In inheritance, the child class acquires the properties and can
access all the data members and functions defined in the
parent class. A child class can also provide its specific
implementation to the functions of the parent class.
• Types of Inheritance:
1) Single Inheritance
2) Multilevel Inheritance
3) Multiple Inheritance
4) Hierarchical Inheritance
Single Inheritance
• The capability of a class to derive properties and
characteristics from another class is called Inheritance.
Inheritance is one of the most important feature of Object
Oriented Programming.
Sub Class: The class that inherits properties from another
class is called Sub class or Derived Class.
Super Class:The class whose properties are inherited by sub
class is called Base Class or Super class.
Single Inheritance
Syntax:
class derived-class(base class):
<class-suite>
Example:
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
class Person():

def __init__(self, name):


self.name = name

def getName(self):
return self.name

def isEmployee(self):
return False

class Employee(Person):

def isEmployee(self):
return True

emp = Person("Geek1")
print(emp.getName(), emp.isEmployee())

emp = Employee("Geek2")
print(emp.getName(), emp.isEmployee())
Multi-Level inheritance

• Multi-level inheritance is achieved when a derived


class inherits another derived class. There is no limit
on the number of levels up to which, the multi-level
inheritance is archived in python.
• Syntax:
class class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>
Example:
class Animal:
def speak(self):
print("Animal Speaking")

#The child class Dog inherits the base class Animal


class Dog(Animal):
def bark(self):
print("dog barking")

#The child class Dogchild inherits another child class Dog


class DogChild(Dog):
def eat(self):
print("Eating bread...")

d = DogChild()
d.bark()
d.speak()
d.eat()
Multiple inheritance

• Python provides us the flexibility to inherit multiple base classes in


the child class.
• Syntax:
class Base1:
<class-suite>

class Base2:
<class-suite>
.
.
.
class BaseN:
<class-suite>

class Derived(Base1, Base2, ...... BaseN):


Example:
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(d.Summation(10,20))
print(d.Multiplication(10,20))
print(d.Divide(10,20))
Hierarchical Inheritance
• Hierarchical inheritance involves multiple
inheritance from the same base or parent
class.
class Parent:
def func1(self):
print("this is function 1")
class Child(Parent):
def func2(self):
print("this is function 2")
class Child2(Parent):
def func3(self):
print("this is function 3")

ob = Child()
ob1 = Child2()
ob.func1()
ob.func2()
Method Overriding
• We can provide some specific implementation of the
parent class method in our child class. When the
parent class method is defined in the child class
with some specific implementation, then the
concept is called method overriding. We may need
to perform method overriding in the scenario where
the different definition of a parent class method is
needed in the child class
Example:
class Animal:
def speak(self):
print("speaking")
class Dog(Animal):
def speak(self):
print("Barking")
d = Dog()
d.speak()
Super () method

class Animal:
def speak(self):
print("speaking")
class Dog(Animal):
def speak(self):
super().speak()
print("Barking")
d = Dog()
d.speak()
Composition Classes
• Composition is a concept that models a has a relationship. It enables creating
complex types by combining objects of other types.

• This means that a class Composite can contain an object of another


class Component. This relationship means that a Composite has a Component.

• Classes that contain objects of other classes are usually referred to as


composites, where classes that are used to create more complex types are
referred to as components.

• For example, your Horse class can be composed by another object of type Tail.
Composition allows you to express that relationship by saying a Horse has
a Tail.

• Composition enables you to reuse code by adding objects to other objects, as


opposed to inheriting the interface and implementation of other classes.

• Both Horse and Dog classes can leverage the functionality of Tail through
class Salary:
def __init__(self, pay):
self.pay = pay
def get_total(self):
return (self.pay*12)

class Employee:
def __init__(self, pay, bonus):
self.pay = pay
self.bonus = bonus
self.obj_salary = Salary(self.pay)
def annual_salary(self):
return "Total: " + str(self.obj_salary.get_total() + self.bonus)
obj_emp = Employee(600, 500)
print(obj_emp.annual_salary())
# specializing inherited methods

class Super:
def method(self):
print("In super.method")
def delegate(self):
self.action()

class Inheritor(Super):
print('\n'"Inheritor....")
pass

class Replacer(Super):
def method(self):
print('\n'"Replacer....")
print("In Replacer.method")

class Extender(Super):
def method(self):
print('\n'"Extender....")
Super.method(self)
print("In Extender.method")

class Provider(Super):
def action(self):
print('\n'"Provider....")
i = Inheritor()
r = Replacer()
e = Extender()

i.method()
r.method()
e.method()

x = Provider()
x.delegate()
O U
K Y
A N
TH

You might also like