• Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements
CODE OF GEEKS

We at CODE OF GEEKS, aim at providing best and quality content for our users at no extra cost.

    • Study Materials
      • InfyTQ Archive
      • Infosys Archive
      • TCS Archive
      • Accenture Archive
      • AMCAT Archive
      • Capgemini Archive
      • Cisco Archive
      • CoCubes Archive
      • Cognizant(CTS) Archive
      • Deloitte Archive
      • DXC Archive
      • Goldman Sachs Archive
      • Hexaware Technologies Archive
      • LTI Archive
      • MindTree Archive
      • Virtusa Archive
      • Wipro Archive
    • Interview Preparation
      • C Interview Questions
      • Data Structures Interview Questions
      • DBMS Interview Questions
      • HR Interview Questions
      • Java Interview Questions
      • Operating System Interview Questions
      • Python Interview Questions
      • SQL Query Interview Questions
    • Tutorials
      • Node.js Tutorial
      • Express.js Tutorial
      • Python Tutorial
    • Programming
      • C Programming MCQs
      • C Code Snippets – Output Questions
      • Python Code Snippets – Output Questions
      • Java Code Snippets – Output Questions
    • Aptitude
      • Verbal Ability for Placements
CODE OF GEEKS
CODE OF GEEKS
  • Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements

Abstract Classes and Abstract Methods in Python

  • December 30, 2022
  • CODE OF GEEKS
  • 0
Abstract Classes and Abstract Methods in Python
Abstract Classes and Abstract Methods in Python

Abstract Classes and Abstract Methods in Python are useful to implement the concepts of Abstraction in Python.

Abstraction refers to the act of hiding background details from the end-user and only displaying the necessary details needed to carry out the basic operations. Abstraction is one of the key principle of Object Oriented Programming.

The principle of Abstraction mainly focuses on ‘WHAT’ not on ‘HOW’. Like, what is a particular thing, not how it’s developed.



Example of Abstraction in real life:

1. If you belong to 18+ age group, then, you must have rode a bike. You only know the basic details that are essential to ride a bike, like acceleration, clutch usage, gear change etc.
You don’t give a damn about how internal operations are happening like energy conversions, wiring etc.
This is Abstraction in real world.

Let’s see how we implement Abstraction in Python using Abstract Class and Abstract Method.

Abstract Method in Python

An abstract method in Python is a method that is marked with a decorator @abstractmethod. Abstract methods are generally written without the body, (they are declared not defined). Their definition is eventually provided in the subsequent subclasses, however, there is no harm in writing an abstract method with a body.

Syntax

class Main(ABC): # abstract class
  @abstractmethod 
  def fun(self):
    pass

A normal class cannot have abstract methods inside it rather they are included in abstract class.



Abstract Class in Python

An abstract class is a class that generally contains atleast one abstract method. We (PVMs) can not create objects for abstract classes but an abstract class can be inherited.

It is considered as the best practice to create subclasses and implement all the abstract methods of an abstract class. Thereafter, we can create objects for these subclasses (remember, they are just like normal class).

Creating an abstract class in Python

The best way to create an abstract class in python is to derive it from the meta class ABC.

Python provides abc module to use the abstraction in our Python program. Please note that it is important to import abc module in our Python program to use the concept of Abstract Class.

from abc import ABC, abstractmethod
class Abstract(ABC):

In the above code, abc is abstract base class and abstractmethod is a decorator.

EXTRA GYAN !!

A meta class is a class that defines the behavior of other classes.

Let’s see one complete python program implementing the concept of abstract classes and abstract methods:

from abc import ABC, abstractmethod # importing ABC from module abc

# Calculator is our abstract class inheriting meta class
class Calculator(ABC):
    
    # let's declare abstract method using decorator
    # definition for this method is provided in subclasses
    @abstractmethod
    def get_result(self, num):
        pass # no code sir

# subclass to calculate Square of a number
class Square(Calculator):
    def get_result(self, num):
        print('Square of number {0}: {1}'.format(num, num ** 2))

# subclass to calculate Cube of a number
class Cube(Calculator):
    def get_result(self, num):
        print('Cube of number {0}: {1}'.format(num, num ** 3))

# subclass to calculate Log of a number
import math
class Log(Calculator):
    def get_result(self, num):
        print('Log of number {0}: {1}'.format(num, math.log(num)))

# creating object of subclass
s = Square()
s.get_result(10)

# creating object of subclass
c = Cube()
c.get_result(10)

# creating object of subclass
l = Log()
l.get_result(1)

O/P

Square of number 10: 100
Cube of number 10: 1000
Log of number 1: 0.0

In the above code,

Calculator: Our abstract class
Square, Cube, Log: Our subclasses
get_result(): Our abstract method
@classmethod: A decorator used to specify the abstract method

You must have observed that our abstract method get_result is implementated as per the requirements i.e for different tasks.

Above code is also an example of other OOPs principle:
1. Inheritance: Observe the Single Inheritance in the above code. Know more here.
2. Polymorphism: Same method being used in different ways.



Few Important points on Abstract classes

* An abstract class can contain both abstract methods or non abstract methods.

* An abstract class is known to perform different tasks through different implementations of its methods in subclasses.

* An abstract class will become an interface when it contains only abstract methods.

* An abstract class is useful when there are some common features to be shared by many objects.

* Abstract class (Abstract method) is also an example of Polymorphism in Python.

That’s all here.

NEXT TUTORIAL>> Errors in Python



Tags: Abstract classes and abstract methods in PythonDefining abstract classes with ABC moduleImplementing abstract methods in Python subclassesImplementing abstraction in PythonInheriting abstract classes in PythonPrinciples of abstraction in object-oriented programmingPython ABC module for abstract classesPython abstract class syntax and usagePython abstract class vs. interfaceUnderstanding abstraction in PythonUsing abstract methods in Python
  • Previous Types of Errors in Python with examples
  • Next InfyTQ Certification Exam 2023-2024 Batch

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Advertise with us

Table of Content – Python

  1. Introduction to Python ▼
    • Python and its features
    • Key Differences : C vs Python
    • Key Differences : Java vs Python
    • Python Flavors
    • PVM and Memory Management in Python

  2. Python Fundamentals ▼
    • 'Hello World' using Python
    • Comments in Python
    • Variables and Garbage Collection in Python
    • Datatypes in Python
    • Determining the Datatype of Literal | type() method
    • Tokens in Python
    • Keywords in Python
    • Identifiers and Naming Convention in Python
    • Literals in Python

  3. Python Operators ▼
    • Operators in Python
    • Python Mathematical Functions

  4. Python User Inputs ▼
    • Taking Inputs | input() function in Python

  5. Python Control Statements ▼
    • Control Statements in Python
    • if-elif-else Statements in Python
    • Looping in Python
    • while loop in Python
    • while-else loop in Python
    • for loop in Python
    • for-else loop in Python
    • Infinite loops in Python
    • Nested loops in Python
    • break Statement in Python
    • continue Statement in Python
    • pass Statement in Python
    • assert Statement in Python
    • return Statement in Python

  6. Python Functions ▼
    • Introduction to Python Functions
    • Python Functions vs Python Methods
    • Local and Global Variables in Python
    • Formal and Actual Arguments in Python
    • Recursion in Python Functions
    • Lambda Functions in Python
    • Function Decorators in Python
    • Function Generators in Python

  7. Python Strings ▼
    • Strings in Python and Basic Operations
    • String Immutability Explained
    • strip() method in Strings
    • find() method in Strings
    • count() method in Strings
    • replace() method in Strings
    • split() method in Strings
    • Switching Cases in Strings
    • startswith() method in Strings
    • endswith() method in Strings

  8. Python Lists ▼
    • Python Lists Basics
    • index() method in list
    • append() method in list
    • insert() method in list
    • copy() method in list
    • remove() method in list
    • pop() method in list
    • sort() method in list
    • reverse() method in list
    • clear() method in list
    • Nested Lists in Python
    • List Comprehensions in Python

  9. Python Sets ▼
    • Python Sets and Basic Operations
    • Adding Elements in Python Sets
    • Removing Elements in Python Sets
    • Union in Python Sets
    • Intersection in Python Sets

  10. Python Tuples ▼
    • Python Tuple Basics
    • Python Tuples Immutability Explained
    • Python Tuples Methods
    • Python Nested Tuples

  11. Python Dictionary ▼
    • Python Dictionary Basics
    • Python Dictionary Sorting
    • Python Dictionary List to Dictionary Conversion
    • Passing Dictionary to Function

  12. Python Classes and Objects ▼
    • Classes and Objects
    • self variable in Python
    • __init__() method in Python
    • Inner Classes
    • Instance variable and methods
    • Class variable and methods

  13. Python OOPs ▼
    • Inheritance and its types
    • super() method in Python
    • Abstract class| Abstract method in Python

  14. Python Exception Handling ▼
    • Errors in Python and its types
    • Exception Handling in Python
    • Types of Exceptions in Python
    • Custom Exceptions in Python

  15. Python File Handling ▼
    • File Handling in Python
    • with statement in Python

  16. Python DateTime Modules ▼
    • datetime module in Python

  17. Python MultiThreading ▼
    • Multithreading in Python

  18. Python Requests Module ▼
    • Python GET Request
    • Python POST Request
    • Python PUT Request

Python Programs

  1. Fibonacci Series till 'N' Numbers

  2. Sum of Digits of a Number

  3. Checking Prime Number

  4. Checking Armstrong Number

  5. Finding Reverse Number (Traditional)

  6. Finding Reverse Number (Pythonic)

  7. Finding Prime Numbers within Range

  8. Finding Prime Numbers within Range Using SOE

  9. Checking Leap year

  10. Calculating Simple Interest

  11. Generate Random Numbers

  12. Calculate Compound Interest

  13. Area of Circle

  14. ASCII Value of Character
CODE OF GEEKS

Subscribe to Newsletter

CODE OF GEEKS

Learn | Code | Achieve

Reach us

[email protected]
We at CODE OF GEEKS, aim at providing quality content to our users at no cost.
CODE OF GEEKS

Important Pages

About us
Advertise
Privacy Policy
Terms and Conditions
Refund Policy
Contact us

Placements – Study Materials

TCS NQT     Wipro     CapGemini
Accenture     MindTree     CTS
DXC     Hexaware Technologies     AMCAT
CoCubes     Goldman Sachs     Dell
Cisco     Deloitte     Virtusa     LTI     Infosys   

Tutorials

Python
Node.js
Express.js
Golang

Recent Posts

Strings in Go and its basic operations
  • August 11, 2023
Introduction to Functions in Go programming
  • August 11, 2023

Copyright @ CODE OF GEEKS. All Rights Reserved.