SlideShare a Scribd company logo
3
Most read
8
Most read
13
Most read
Abstract Classes And
Interfaces
Team Emertxe
Introduction
Introduction
Example:
To understand that Myclass method is shared by all objects
class Myclass:
def calculate(self, x):
print("Square: ", x * x)
#All objects share same calculate() method
obj1 = Myclass()
obj1.calculate(2)
obj2 = Myclass()
obj2.calculate(3)
obj3 = Myclass()
obj3.calculate(4)
Question

What If?

Object-1 wants to calculate square value

Object-2 wants to calculate square root

Object-3 wants to calculate Cube
Solution-1

Define, three methods in the same class

calculate_square()

calculate_sqrt()

calculate_cube()

Disadvantage:

All three methods are available to all the objects which is not advisable
Solution-2
calculate(x):
no body
calculate(x):
square of x
calculate(x):
sqrt of x
calculate(x):
cube of x
Obj1 Obj2 Obj3
Myclass
Sub1 Sub2 Sub3
Abstract Method and Class
Abstract Method & Class

Abstract Method

- Is the method whose action is redefined in sub classes as per the requirements

of the objects

- Use decorator @abstractmethod to mark it as abstract method

- Are written without body

Abstract Class

- Is a class generally contains some abstract methods

- PVM cannot create objects to abstract class, since memory needed will not be

known in advance

- Since all abstract classes should be derived from the meta class ABC which belongs to
abc(abstract base class) module, we need to import this module

- To import abstract class, use

- from abc import ABC, abstractmethod

OR

- from abc import *
Program-1
#To create abstract class and sub classes which implement the abstract method of the
abstract class
from abc import ABC, abstractmethod
class Myclass(ABC):
@abstractmethod
def calculate(self, x):
pass
#Sub class-1
class Sub1(Myclass):
def calculate(self, x):
print("Square: ", x * x)
Obj1 = Sub1()
Obj1.calculate(2)
Obj2 = Sub2()
Obj2.calculate(16)
Obj3 = Sub3()
Obj2.calculate(3)
#Sub class-2
import math
class Sub2(Myclass):
def calculate(self, x):
print("Square root: ", math.sqrt(x))
#Sub class-3
class Sub3(Myclass):
def calculate(self, x):
print("Cube: ", x * x * x)
Example-2

Maruthi, Santro, Benz are all objects of class Car
Registration no. - All cars will have reg. no.
- Create var for it
Fuel Tank - All cars will have common fule tank
- Action: Open, Fill, Close
Steering - All cars will not have common steering
say, Maruthi uses- Manual steering
Santro uses - Power steering
- So define this as an Abstract Method
Brakes - Maruthi uses hydraulic brakes
- Santro uses gas brakes
- So define this as an Abstract Method
Program-2
#Define an absract class
from abc import *
class Car(ABC):
def __init__(self, reg_no):
self.reg_no = reg_no
def opentank(self):
print("Fill the fuel for car with reg_no: ",
self.reg_no)
@abstractmethod
def steering(self):
pass
@abstractmethod
def braking(self):
pass
#Define the Maruthi class
from abstract import Car
class Maruthi(Car):
def steering(self):
print("Maruthi uses Manual steering")
def braking(self):
print("Maruthi uses hydraulic braking system")
#Create the objects
Obj = Maruthi(123)
Obj.opentank()
Obj.steering()
Obj.braking()
Interfaces
Interfaces

Abstract classes contains both,

- Abstract methods

- Concrete Methods

Interfaces is also an Abstract class, but contains only

- Abstract methods

Plus point of Interface.

- Every sub-class may provide its own implementation for the abstract methods
Interfaces
Program-1
from abc import *
class Myclass(ABC):
@abstractmethod
def connect(self):
pass
@abstractmethod
def disconnect(self):
pass
#Define Database
class Database:
str = input("Enter the database name: ")
#Covert the string into the class name
classname = globals()[str]
#create an object
x = classname()
#Call methods
x.connect()
x.disconnect()
#Sub-Class:1
class Oracle(Myclass):
def connect(self):
print("Connecting to oracle database...")
def disconnect(self):
print("Disconnecting from oracle
database...")
#Sub-Class:2
class Sybase(Myclass):
def connect(self):
print("Connecting to sybase database...")
def disconnect(self):
print("Disconnecting from sybase
database...")
Interfaces
Program-2
from abc import *
class Myclass(ABC):
@abstractmethod
def putdata(self, text):
pass
@abstractmethod
def disconnect(self):
pass
#Define Printer
class Printer:
str = input("Enter the printer name: ")
#Covert the string into the class name
classname = globals()[str]
#create an object
x = classname()
#Call methods
x.putdata("Sending to printer")
x.disconnect()
#Sub-Class:1
class IBM(Myclass):
def putdata(self, text):
print(text)
def disconnect(self):
print("Disconnecting from IBM printer...")
#Sub-Class:2
class Epson(Myclass):
def putdata(self, text):
print(text)
def disconnect(self):
print("Disconnecting from Epson printer...")
THANK YOU

More Related Content

What's hot (20)

PDF
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
PPTX
Python-DataAbstarction.pptx
Karudaiyar Ganapathy
 
PPTX
Polymorphism in Python
Home
 
PPTX
Constructor in java
Pavith Gunasekara
 
PPTX
Python-Inheritance.pptx
Karudaiyar Ganapathy
 
PPTX
Python: Modules and Packages
Damian T. Gordon
 
PPTX
Static Data Members and Member Functions
MOHIT AGARWAL
 
PPSX
Modules and packages in python
TMARAGATHAM
 
PDF
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Edureka!
 
PPTX
Constructor overloading & method overloading
garishma bhatia
 
ODP
Python Modules
Nitin Reddy Katkam
 
PPTX
Basics of Object Oriented Programming in Python
Sujith Kumar
 
PDF
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
PPTX
classes and objects in C++
HalaiHansaika
 
PPTX
Python-Polymorphism.pptx
Karudaiyar Ganapathy
 
PPTX
Chapter 07 inheritance
Praveen M Jigajinni
 
PPTX
Chapter 05 classes and objects
Praveen M Jigajinni
 
PPTX
Polymorphism in java
Elizabeth alexander
 
PPTX
CLASS OBJECT AND INHERITANCE IN PYTHON
Lalitkumar_98
 
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
Python-DataAbstarction.pptx
Karudaiyar Ganapathy
 
Polymorphism in Python
Home
 
Constructor in java
Pavith Gunasekara
 
Python-Inheritance.pptx
Karudaiyar Ganapathy
 
Python: Modules and Packages
Damian T. Gordon
 
Static Data Members and Member Functions
MOHIT AGARWAL
 
Modules and packages in python
TMARAGATHAM
 
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Edureka!
 
Constructor overloading & method overloading
garishma bhatia
 
Python Modules
Nitin Reddy Katkam
 
Basics of Object Oriented Programming in Python
Sujith Kumar
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
classes and objects in C++
HalaiHansaika
 
Python-Polymorphism.pptx
Karudaiyar Ganapathy
 
Chapter 07 inheritance
Praveen M Jigajinni
 
Chapter 05 classes and objects
Praveen M Jigajinni
 
Polymorphism in java
Elizabeth alexander
 
CLASS OBJECT AND INHERITANCE IN PYTHON
Lalitkumar_98
 

Similar to Python programming : Abstract classes interfaces (20)

PPTX
Design and Analysis of Algorithm in Compter Science.pptx
rahulshawit2023
 
PDF
Memory Management C++ (Peeling operator new() and delete())
Sameer Rathoud
 
PDF
Refactoring Chapter11
Abner Chih Yi Huang
 
PDF
exercises_for_live_coding_Java_advanced-2.pdf
enodani2008
 
PPTX
Chap2 class,objects
raksharao
 
PDF
Ooabap notes with_programs
Kranthi Kumar
 
PDF
Ooabapnoteswithprogram good 78
Yogesh Mehra
 
DOCX
Data analysis and algorithm analysis presentation
ShafiEsa1
 
PPTX
Data Structures and Algorithms in Python
JakeLWright
 
PDF
Lecture 5
Muhammad Fayyaz
 
PPT
Chap08
Terry Yoast
 
PPTX
CSssssssssssss2030DE_Lab 1_final-111.pptx
TangChingXian
 
PDF
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
info309708
 
DOCX
B61301007 matlab documentation
Manchireddy Reddy
 
PPTX
Presentation 1st
Connex
 
PPTX
Divide and Conquer / Greedy Techniques
Nirmalavenkatachalam
 
PDF
OO_ABAP_BASIC_CONCEPTS_1741540582ete.pdf
nalimelavishnuvardha1
 
PDF
10. haskell Modules
Sebastian Rettig
 
PPTX
PYTHON-PROGRAMMING-UNIT-II.pptx gijtgjjgg jufgiju yrguhft hfgjutt jgg
DeepakRattan3
 
PDF
Please the following is the currency class of perious one- class Curre.pdf
admin463580
 
Design and Analysis of Algorithm in Compter Science.pptx
rahulshawit2023
 
Memory Management C++ (Peeling operator new() and delete())
Sameer Rathoud
 
Refactoring Chapter11
Abner Chih Yi Huang
 
exercises_for_live_coding_Java_advanced-2.pdf
enodani2008
 
Chap2 class,objects
raksharao
 
Ooabap notes with_programs
Kranthi Kumar
 
Ooabapnoteswithprogram good 78
Yogesh Mehra
 
Data analysis and algorithm analysis presentation
ShafiEsa1
 
Data Structures and Algorithms in Python
JakeLWright
 
Lecture 5
Muhammad Fayyaz
 
Chap08
Terry Yoast
 
CSssssssssssss2030DE_Lab 1_final-111.pptx
TangChingXian
 
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
info309708
 
B61301007 matlab documentation
Manchireddy Reddy
 
Presentation 1st
Connex
 
Divide and Conquer / Greedy Techniques
Nirmalavenkatachalam
 
OO_ABAP_BASIC_CONCEPTS_1741540582ete.pdf
nalimelavishnuvardha1
 
10. haskell Modules
Sebastian Rettig
 
PYTHON-PROGRAMMING-UNIT-II.pptx gijtgjjgg jufgiju yrguhft hfgjutt jgg
DeepakRattan3
 
Please the following is the currency class of perious one- class Curre.pdf
admin463580
 
Ad

More from Emertxe Information Technologies Pvt Ltd (20)

Ad

Recently uploaded (20)

PDF
Bridging CAD, IBM TRIRIGA & GIS with FME: The Portland Public Schools Case
Safe Software
 
PDF
LLM Search Readiness Audit - Dentsu x SEO Square - June 2025.pdf
Nick Samuel
 
PDF
DoS Attack vs DDoS Attack_ The Silent Wars of the Internet.pdf
CyberPro Magazine
 
PDF
Understanding The True Cost of DynamoDB Webinar
ScyllaDB
 
PDF
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
PDF
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
PDF
Unlocking FME Flow’s Potential: Architecture Design for Modern Enterprises
Safe Software
 
PPTX
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 
PDF
Automating the Geo-Referencing of Historic Aerial Photography in Flanders
Safe Software
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Pitch ...
Michele Kryston
 
PDF
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PPTX
Reimaginando la Ciberdefensa: De Copilots a Redes de Agentes
Cristian Garcia G.
 
PDF
Simplify Your FME Flow Setup: Fault-Tolerant Deployment Made Easy with Packer...
Safe Software
 
PDF
Redefining Work in the Age of AI - What to expect? How to prepare? Why it mat...
Malinda Kapuruge
 
PPTX
Mastering Authorization: Integrating Authentication and Authorization Data in...
Hitachi, Ltd. OSS Solution Center.
 
PPTX
Practical Applications of AI in Local Government
OnBoard
 
PDF
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
PDF
Plugging AI into everything: Model Context Protocol Simplified.pdf
Abati Adewale
 
PDF
“Scaling i.MX Applications Processors’ Native Edge AI with Discrete AI Accele...
Edge AI and Vision Alliance
 
Bridging CAD, IBM TRIRIGA & GIS with FME: The Portland Public Schools Case
Safe Software
 
LLM Search Readiness Audit - Dentsu x SEO Square - June 2025.pdf
Nick Samuel
 
DoS Attack vs DDoS Attack_ The Silent Wars of the Internet.pdf
CyberPro Magazine
 
Understanding The True Cost of DynamoDB Webinar
ScyllaDB
 
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
Unlocking FME Flow’s Potential: Architecture Design for Modern Enterprises
Safe Software
 
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 
Automating the Geo-Referencing of Historic Aerial Photography in Flanders
Safe Software
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Pitch ...
Michele Kryston
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Reimaginando la Ciberdefensa: De Copilots a Redes de Agentes
Cristian Garcia G.
 
Simplify Your FME Flow Setup: Fault-Tolerant Deployment Made Easy with Packer...
Safe Software
 
Redefining Work in the Age of AI - What to expect? How to prepare? Why it mat...
Malinda Kapuruge
 
Mastering Authorization: Integrating Authentication and Authorization Data in...
Hitachi, Ltd. OSS Solution Center.
 
Practical Applications of AI in Local Government
OnBoard
 
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
Plugging AI into everything: Model Context Protocol Simplified.pdf
Abati Adewale
 
“Scaling i.MX Applications Processors’ Native Edge AI with Discrete AI Accele...
Edge AI and Vision Alliance
 

Python programming : Abstract classes interfaces

  • 3. Introduction Example: To understand that Myclass method is shared by all objects class Myclass: def calculate(self, x): print("Square: ", x * x) #All objects share same calculate() method obj1 = Myclass() obj1.calculate(2) obj2 = Myclass() obj2.calculate(3) obj3 = Myclass() obj3.calculate(4)
  • 4. Question  What If?  Object-1 wants to calculate square value  Object-2 wants to calculate square root  Object-3 wants to calculate Cube
  • 5. Solution-1  Define, three methods in the same class  calculate_square()  calculate_sqrt()  calculate_cube()  Disadvantage:  All three methods are available to all the objects which is not advisable
  • 6. Solution-2 calculate(x): no body calculate(x): square of x calculate(x): sqrt of x calculate(x): cube of x Obj1 Obj2 Obj3 Myclass Sub1 Sub2 Sub3
  • 8. Abstract Method & Class  Abstract Method  - Is the method whose action is redefined in sub classes as per the requirements  of the objects  - Use decorator @abstractmethod to mark it as abstract method  - Are written without body  Abstract Class  - Is a class generally contains some abstract methods  - PVM cannot create objects to abstract class, since memory needed will not be  known in advance  - Since all abstract classes should be derived from the meta class ABC which belongs to abc(abstract base class) module, we need to import this module  - To import abstract class, use  - from abc import ABC, abstractmethod  OR  - from abc import *
  • 9. Program-1 #To create abstract class and sub classes which implement the abstract method of the abstract class from abc import ABC, abstractmethod class Myclass(ABC): @abstractmethod def calculate(self, x): pass #Sub class-1 class Sub1(Myclass): def calculate(self, x): print("Square: ", x * x) Obj1 = Sub1() Obj1.calculate(2) Obj2 = Sub2() Obj2.calculate(16) Obj3 = Sub3() Obj2.calculate(3) #Sub class-2 import math class Sub2(Myclass): def calculate(self, x): print("Square root: ", math.sqrt(x)) #Sub class-3 class Sub3(Myclass): def calculate(self, x): print("Cube: ", x * x * x)
  • 10. Example-2  Maruthi, Santro, Benz are all objects of class Car Registration no. - All cars will have reg. no. - Create var for it Fuel Tank - All cars will have common fule tank - Action: Open, Fill, Close Steering - All cars will not have common steering say, Maruthi uses- Manual steering Santro uses - Power steering - So define this as an Abstract Method Brakes - Maruthi uses hydraulic brakes - Santro uses gas brakes - So define this as an Abstract Method
  • 11. Program-2 #Define an absract class from abc import * class Car(ABC): def __init__(self, reg_no): self.reg_no = reg_no def opentank(self): print("Fill the fuel for car with reg_no: ", self.reg_no) @abstractmethod def steering(self): pass @abstractmethod def braking(self): pass #Define the Maruthi class from abstract import Car class Maruthi(Car): def steering(self): print("Maruthi uses Manual steering") def braking(self): print("Maruthi uses hydraulic braking system") #Create the objects Obj = Maruthi(123) Obj.opentank() Obj.steering() Obj.braking()
  • 13. Interfaces  Abstract classes contains both,  - Abstract methods  - Concrete Methods  Interfaces is also an Abstract class, but contains only  - Abstract methods  Plus point of Interface.  - Every sub-class may provide its own implementation for the abstract methods
  • 14. Interfaces Program-1 from abc import * class Myclass(ABC): @abstractmethod def connect(self): pass @abstractmethod def disconnect(self): pass #Define Database class Database: str = input("Enter the database name: ") #Covert the string into the class name classname = globals()[str] #create an object x = classname() #Call methods x.connect() x.disconnect() #Sub-Class:1 class Oracle(Myclass): def connect(self): print("Connecting to oracle database...") def disconnect(self): print("Disconnecting from oracle database...") #Sub-Class:2 class Sybase(Myclass): def connect(self): print("Connecting to sybase database...") def disconnect(self): print("Disconnecting from sybase database...")
  • 15. Interfaces Program-2 from abc import * class Myclass(ABC): @abstractmethod def putdata(self, text): pass @abstractmethod def disconnect(self): pass #Define Printer class Printer: str = input("Enter the printer name: ") #Covert the string into the class name classname = globals()[str] #create an object x = classname() #Call methods x.putdata("Sending to printer") x.disconnect() #Sub-Class:1 class IBM(Myclass): def putdata(self, text): print(text) def disconnect(self): print("Disconnecting from IBM printer...") #Sub-Class:2 class Epson(Myclass): def putdata(self, text): print(text) def disconnect(self): print("Disconnecting from Epson printer...")