curriculum/challenges/english/blocks/lecture-understanding-abstraction/68c3bc80f67363a31791fe1c.md
Now that we've looked at encapsulation, inheritance, and polymorphism, let's discuss the next key concept of object-oriented programming – abstraction.
Abstraction is the process of hiding complex implementation details and showing only the essential features of an object or system. Think of it as focusing on what something does rather than how it does it.
Abstraction is not limited to Python. It's a programming concept that can be implemented in many languages that support object-oriented programming.
To illustrate abstraction, imagine you're driving a car. When you're in the driver's seat, you interact with essential parts like the steering wheel, shifter, and the accelerator and brake pedals. You don't need to know the intricate details of how engine works, how the transmission shifts gears, or the physics behind the braking system, as all of those are the complex implementation details.
That's an abstraction at work! It provides you with a simplified interface to interact with a complex system.
In the case of a car again, the simplified interface is the steering wheel, brakes, and accelerator, while the complex system is the car itself.
As for how Python implements abstraction, it does so through the abc module.
This module provides the ABC class (standing for “abstract base class”) and the @abstractmethod decorator.
ABC is the class that is meant to be inherited from, but you cannot create direct objects from it. It is what defines a common interface of methods and properties that its subclasses must implement.
On the other hand, an abstract method is a method declared in an Abstract Base Class (ABC) using the @abstractmethod decorator. It may have no implementation or a basic default one. However, any subclass must override it to be considered concrete and instantiable, even if a default implementation is provided.
Here's the basic syntax of abstract class in Python:
from abc import ABC, abstractmethod
# Define an abstract base class
class AbstractClass(ABC):
@abstractmethod
def abstract_method(self):
pass
# Concrete subclass that implements the abstract method
class ConcreteClassOne(AbstractClass):
def abstract_method(self):
print('Implementation in ConcreteClassOne')
# Another concrete subclass
class ConcreteClassTwo(AbstractClass):
def abstract_method(self):
print('Implementation in ConcreteClassTwo')
Here's a basic example:
from abc import ABC, abstractmethod
class Animal(ABC): # Inherits from abstract base class
@abstractmethod # Abstract method decorator
def make_sound(self): # The method subclasses must override
pass
# Concrete class that will override the abstract method
class Dog(Animal):
def make_sound(self):
print('Woof!')
# Another concrete class that will override the abstract method
class Cat(Animal):
def make_sound(self):
print('Meow!')
# Another concrete class that will override the abstract method
class Monkey(Animal):
def make_sound(self):
print('Ooh ooh aah aah!')
# Create instances of each concrete class
animals = [Dog(), Cat(), Monkey()]
# Loop through the instances to call the make_sound method
for animal in animals:
animal.make_sound()
# Output:
# Woof!
# Meow!
# Ooh ooh aah aah!
In this example:
ABC class and abstractmethod from the abc module.Animal class that inherits from ABC, and create an abstract method make_sound in it that each subclass of Animal must override.Dog, Cat, and Monkey, which must override the make_sound abstract method.make_sound method to show how each of them implements the make_sound abstract method in its own way.Remember that you cannot create an instance of the Animal class. Here's what happens if you try to do that:
dog = Animal()
# TypeError: Can't instantiate abstract class Animal
# without an implementation for abstract method 'make_sound'
The same rule applies to subclasses that don't provide an implementation for the abstract method. Even if you define a subclass of Animal, you can't instantiate it until it overrides make_sound. Here's an example showing that:
class Bird(Animal):
pass
bird = Bird()
# TypeError: Can't instantiate abstract class Bird
# without an implementation for abstract method 'make_sound'
Here's another example, this time with an instance attribute you can pass to the instances of the concrete methods:
from abc import ABC, abstractmethod
# The blueprint for any toy that can speak
class TalkingToy(ABC):
def __init__(self, name):
self.name = name
@abstractmethod
def speak(self):
pass
class RobotToy(TalkingToy):
def speak(self):
print(f'{self.name} says beep boop! I am a robot!')
class TeddyBearToy(TalkingToy):
def speak(self):
print(f"{self.name} says hug me! I'm cuddly!")
class DinosaurToy(TalkingToy):
def speak(self):
print(f'{self.name} says ROOOOAR!')
# Create toys
rusty = RobotToy('Rusty')
fluffy = TeddyBearToy('Fluffy')
rex = DinosaurToy('Rex')
toys = [rusty, fluffy, rex]
for toy in toys:
toy.speak()
# Output:
# Rusty says beep boop! I am a robot!
# Fluffy says hug me! I'm cuddly!
# Rex says ROOOOAR!
In this example:
TalkingToy that defines a blueprint for any toy that can speak.RobotToy, TeddyBearToy, and DinosaurToy implement the speak method in their own way.speak method, each toy speaks in its own unique way.In conclusion, abstraction in Python simplifies complex systems by increasing reusability.
You've seen how you can reuse a single method from an abstract class across multiple subclasses while forcing each subclass to provide its specific behavior.
This approach keeps your code organized, flexible, and easier to maintain, especially as your application grows.
What is the primary goal of abstraction in object-oriented programming?
To expose all internal implementation details to users.
Think about how abstraction simplifies interaction with complex systems.
To merge multiple classes into one.
Think about how abstraction simplifies interaction with complex systems.
To prevent methods from being overridden in child classes.
Think about how abstraction simplifies interaction with complex systems.
To hide complex logic and only show essential features
4
How does Python implement abstraction through its ABC module?
By allowing direct instantiation of abstract classes.
The ABC module enforces method implementation in child classes.
By using decorators and inheritance to define abstract methods that subclasses must implement.
By automatically hiding all methods with double underscores.
The ABC module enforces method implementation in child classes.
By converting classes to functions.
The ABC module enforces method implementation in child classes.
2
In the car analogy for abstraction, what represents the simplified interface and the complex system?
The interface is the engine pistons, and the complex system is the steering wheel.
Think about how the interface is what you directly interact with, while the complex system is how it works.
The interface is the steering wheel, brakes, and accelerator, and the complex system is the engine, transmission, and braking physics.
The interface is the car manual, and the complex system is the dashboard controls.
Think about how the interface is what you directly interact with, while the complex system is how it works.
The interface is the fuel type, and the complex system is the tyres.
Think about how the interface is what you directly interact with, while the complex system is how it works.
2