9 7 Abstraction Explained
Key Concepts
Abstraction in Python involves several key concepts:
- Abstract Classes
- Abstract Methods
- Concrete Methods
- Inheritance and Abstraction
- Practical Applications
1. Abstract Classes
An abstract class is a class that cannot be instantiated on its own and is meant to be subclassed. It serves as a blueprint for other classes.
Example:
from abc import ABC, abstractmethod class Animal(ABC): @abstractmethod def speak(self): pass
2. Abstract Methods
Abstract methods are methods declared in an abstract class that have no implementation. Subclasses of the abstract class must provide an implementation for these methods.
Example:
class Animal(ABC): @abstractmethod def speak(self): pass
3. Concrete Methods
Concrete methods are methods in an abstract class that have a complete implementation. These methods can be inherited and used by subclasses without modification.
Example:
class Animal(ABC): @abstractmethod def speak(self): pass def sleep(self): return "Zzzz..."
4. Inheritance and Abstraction
Inheritance allows subclasses to inherit abstract methods from an abstract class. Subclasses must implement these abstract methods to be instantiated.
Example:
class Dog(Animal): def speak(self): return "Woof!" my_dog = Dog() print(my_dog.speak()) # Output: Woof! print(my_dog.sleep()) # Output: Zzzz...
5. Practical Applications
Abstraction is useful in scenarios where you want to define a common interface for a group of related classes without specifying the implementation details.
Example:
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 class Rectangle(Shape): def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height circle = Circle(5) rectangle = Rectangle(4, 6) print(circle.area()) # Output: 78.5 print(rectangle.area()) # Output: 24