[go: up one dir, main page]

0% found this document useful (0 votes)
2 views21 pages

Abstraction

The document explains the concept of data abstraction in object-oriented programming (OOP), emphasizing its importance in simplifying complex code by hiding unnecessary details while exposing essential functionalities. It discusses how abstraction can be implemented in Python using abstract classes and the abc module, providing examples of abstract and concrete methods. The benefits of data abstraction include improved modularity, better security, simplified complexity, reduced errors, improved maintainability, and enhanced flexibility.
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)
2 views21 pages

Abstraction

The document explains the concept of data abstraction in object-oriented programming (OOP), emphasizing its importance in simplifying complex code by hiding unnecessary details while exposing essential functionalities. It discusses how abstraction can be implemented in Python using abstract classes and the abc module, providing examples of abstract and concrete methods. The benefits of data abstraction include improved modularity, better security, simplified complexity, reduced errors, improved maintainability, and enhanced flexibility.
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/ 21

ABSTRACTION

OOPS
Introduction

• Abstraction hides unnecessary and internal functionality from


users and provides access to helpful information. Therefore,
users interact with basic implementation details without
knowing their inner workings. This means users are aware of
“what a function does” without knowing “how it does it.”
• For example, we may use a smartphone, knowing its different
functions, such as voice recorder, messaging, camera, and
calls. However, we don’t know how the smartphone performs
these operations or what’s happening in the background.
• Another example of Python data abstraction is driving a car. We
know how to use breaks, clutch, and gear but we are not
familiar with what’s happening behind the scenes. Let’s delve
deeper into data abstraction in this tutorial.
Data Abstraction in OOP

• Data abstraction is a powerful and essential concept in object-oriented programming. It


simplifies complex codes and tasks for users by hiding irrelevant details and showing only
the useful parts.
• In programming, there are times when we don’t want to expose or share sensitive details of
code implementation. Hence, we use data abstraction in such cases. For example, when you
go through a tutorial online, you only know that a subject expert prepared it and, at times,
the name of the writer. However, you are not aware of the entire process that goes behind
preparing, editing, and publishing that tutorial because those details are not useful to you.
• For a coder or programmer, data abstraction goes beyond simply hiding a section of
information. For example, if they want to build a program to add or multiply two specific
numbers, they won’t make an effort to develop an app that can add or multiply specifically
those two numbers. The ideal scenario would be to create a program that can add or
multiply any two numbers.
• Therefore, we can say that abstraction separates specific uses of a function from its
generalized purpose. Hence, we can reduce task complexities and build more scalable and
flexible programs.
What Is Data Abstraction in
Python?
• Data abstraction is the process of hiding unnecessary
and complex implementation details from users while
showing only essential details and functionalities. This is
a core concept in object-oriented programming that
allows users to implement complex logic based on the
information provided without bothering with backend
complexities.
• We can achieve Python abstraction by using abstract
classes created through the abstract base class (abc)
module and its @abstractmethod.
Abstraction Classes in Python
• An abstract class is one in which one or more abstract
methods are defined. When we declare a method inside
a class without its implementation, it is called an
abstract method. An abstract class is a blueprint or
template for other classes as it defines a list of methods
a class must implement. A subclass can inherit an
abstract class, and the object of the derived class can
be used to access base class features.
• An abstract class provides the standard interface for
implementations of components, enabling a class to
derive data and functions from the base class. In
Python, we use the abc module for abstraction, and
here is the syntax for it.
• Abstract classes lay down the blueprint and create a
structure to build other classes. Hence, it ensures a
standard set of methods to implement in the derived
classes. Basically, an abstract class dictates a type of
contract and inheriting classes adhere to it by
implementing the methods. The following are the key
components of an abstract class:
• One of the primary features of abstract classes is they
can’t be created or instantiated directly. They are the
base for other classes and are not instantiated
themselves.
• They lay down the template or structure to build other
classes. They provide a blueprint for other classes by
defining methods without implementing them.
Example

• from abc import ABC, abstractmethod


• class Animal(ABC):
• @abstractmethod
• def sound(self):
• pass

• class Dog(Animal):
• def sound(self):
• return "Bark"

• # Creating an object of the Dog class


• dog = Dog()
• print(dog.sound()) # Output: Bark
Using the abc module to import the ABC class.

• For example, we create an abstract class named Car


and derive two subclasses, Kia and Honda, from it. The
two classes implement the methods defined in the
abstract class. The Car class is the parent abstract
class, whereas Kia and Honda are subclasses. We can’t
access methods of the parent class by creating an
object but have to create objects of two derived classes
for it.
Using the abc module to import the ABC class.
• For example, we create an abstract class named Car
and derive two subclasses, Kia and Honda, from it. The
two classes implement the methods defined in the
abstract class. The Car class is the parent abstract
class, whereas Kia and Honda are subclasses. We can’t
access methods of the parent class by creating an
object but have to create objects of two derived classes
for it.
from abc import ABC, abstractmethod
class Car(ABC):
@abstractmethod
def start_engine(self):
pass
@abstractmethod
def stop_engine(self):
pass
class Kia(Car):
def start_engine(self):
return "Kia engine started"
def stop_engine(self):
return "Kia engine stopped"
class Honda(Car):
def start_engine(self):
return "Honda engine started"
def stop_engine(self):
return "Honda engine stopped"
# Creating objects of the derived classes
kia = Kia()
honda = Honda()

# Calling the methods on the objects


print(kia.start_engine()) # Output: Kia engine started
print(kia.stop_engine()) # Output: Kia engine stopped
print(honda.start_engine()) # Output: Honda engine started
print(honda.stop_engine()) # Output: Honda engine stopped
Why use an abstract base class?

• When we define an abstract base class, it allows us to


create a common API for multiple subclasses. This
comes in handy while working in large teams and
codebases, as we don’t need to remember all the
classes.
Working of Abstract Class

• Most high-level programming languages provide the abstract class,


but the abstract method is not a default feature in Python. Therefore,
we achieve this using the abc module that provides the base class and
necessary tools to define Abstract Base Class (ABC).

• The abc module’s @abstractmethod decorator indicates abstract


methods in the base class. Also, it has a virtual subclasses feature.
These are the classes that don’t inherit from a class but are
recognized by
Working of Abstract Class
• The abc module provides the metaclass ABCMeta to
define ABCs, whereas the helper class defines ABCs
through inheritance. While defining ABC, we can create
the abstract methods in the base class by decorating
using the @abstractmethod keyword and register
concrete methods as implementations of the base
class.
• We can create our ABCs as shown:
• The abstract method of the base class tells the child
class to write an implementation of all defined abstract
methods. If it’s not done, the code will throw an error.
Concrete Method in the Abstract
Base Class
• In abstract methods, an implementation may vary for
any subclass, and there must be an implementation
while defining the subclass. However, some methods
have the same implementation for all subclasses. Some
of the features exhibit the properties of an abstract
class and must be implemented in the abstract class;
else all inherited classes will have repetitive code. Such
methods are known as concrete methods.
Concrete Method in the Abstract
Base Class
• In abstract methods, an implementation may vary for
any subclass, and there must be an implementation
while defining the subclass. However, some methods
have the same implementation for all subclasses. Some
of the features exhibit the properties of an abstract
class and must be implemented in the abstract class;
else all inherited classes will have repetitive code. Such
methods are known as concrete methods.
Concrete Method in the Abstract
Base Class
• In Python, concrete methods are defined in the abstract
class with complete implementation and must avoid
code repetition in the subclass. So, if an abstract class
has a method with the same implementation as its
subclasses, we just need to write the implementation of
that particular method in the abstract base class rather
than repeatedly writing the implementation of the
concrete method for every subclass.
Concrete Method in the Abstract
Base Class
• An abstract class can have abstract and concrete
methods. To access the concrete method of an abstract
class, we instantiate an object of a child class, which
also lets us access its abstract methods. However, we
must provide an implementation of the abstract method
in the child class even when it is in the abstract class.
Also, a subclass implements all abstract methods
defined in the parent class; else it can throw an error
Explanation:
Abstract Base Class (MyABC):

• Inherits from ABC and defines two abstract methods,


abstract_method1 and abstract_method2, using the
@abstractmethod decorator. These methods have no
implementation and must be overridden in any concrete subclass.
• Concrete Class (ConcreteClass):
• Inherits from MyABC and provides concrete implementations for
both abstract_method1 and abstract_method2.
• Creating Instances:
• You can create an instance of ConcreteClass and call the
implemented methods.
How to create an abstract base class and
abstract method?

• from abc import ABC, abstractmethod


• class Shape(ABC):
• @abstractmethod
• def area(self):
• pass
• class Circle(Shape):
• def __init__(self, radius):
• self.radius = radius
• def area(self):
• return 3.14 * self.radius ** 2

• # Creating an object of Circle


• circle = Circle(5)
• print(circle.area()) # Output: 78.5
Importance of Python Data
Abstraction
• Data abstraction shows only the most crucial and useful data to users while hiding complex
implementation details. This enables them to design modular and organized code, promotes
code reusability, makes it easier to understand and maintain code, and ensures seamless
collaboration.
• 1. Improved Modularity- Data abstraction helps us create a modular, reusable, and
understandable program. This makes software expandable and adaptable.
• 2. Better Security- It protects sensitive and complex data from unauthorized access,
which enhances the security of data and systems.
• 3. Simplified Complexity- Data abstraction streamlines the code and makes it user-
friendly. This simplification allows users to interact with complex systems intuitively without
bothering about useless and unnecessary details.
• 4. Reduced Errors- As abstraction hides implementation details about data structures from
users, it ensures data integrity. It mitigates the chances of errors and safeguards crucial
data.
• 5. Improved Maintainability- By showing only useful and necessary details and exposing
a consistent interface, abstraction enables developers to modify the underlying code without
hampering the user experience.
• 6. Enhanced Flexibility- Abstraction makes software flexible, so developers can modify
internal code, optimize performance, and add new functionalities without disrupting the user
interface or affecting user interaction.

You might also like