Sobes.tech
Middle
218

What are abstract classes?

Answer from AI

sobes.tech AI

Abstract classes are classes that cannot be instantiated directly. They serve as templates or bases for other classes. The main purpose of abstract classes is to define a common interface for a set of subclasses, requiring them to implement certain methods.

Key features:

  • Cannot create an instance: You cannot create an object directly from an abstract class.
  • Can contain abstract and concrete methods: Abstract methods are declared but not implemented in the abstract class. Subclasses must implement them. Concrete methods have an implementation in the abstract class and are inherited by subclasses.
  • Define an interface: Abstract classes ensure that all subclasses will have a certain set of methods.
  • Used for inheritance: They serve as a foundation for other classes.

In Python, abstract classes are implemented using the abc module (Abstract Base Classes).

import abc

class Animal(abc.ABC): # Declaration of an abstract base class

    @abc.abstractmethod
    def make_sound(self): # Abstract method
        pass

    def walk(self): # Concrete method
        print("Walking...")

class Dog(Animal):
    def make_sound(self): # Mandatory implementation of the abstract method
        print("Woof!")

class Cat(Animal):
    def make_sound(self): # Mandatory implementation of the abstract method
        print("Meow!")

# animal = Animal()  # Will raise TypeError: Can't instantiate abstract class Animal with abstract methods make_sound

dog = Dog()
dog.make_sound()
dog.walk()

cat = Cat()
cat.make_sound()
cat.walk()

Applications:

  • Creating APIs and frameworks.
  • Ensuring uniformity in class hierarchies.
  • Separating interface from implementation.

Difference from interfaces in other languages (e.g., Java):

In Python, abstract classes can contain both abstract and concrete methods, whereas interfaces in Java only contain method signatures (before Java 8/9).

# Example of an interface (conceptually)
# Python does not have a built-in concept of pure interfaces without implementation
# Abstract classes with only abstract methods are used to simulate.
class InterfaceExample(abc.ABC):

    @abc.abstractmethod
    def method1(self):
        pass

    @abc.abstractmethod
    def method2(self):
        pass