What is an abstract class in Python?

What is an abstract class in Python?

a) A class that cannot be instantiated and contains one or more abstract methods
b) A class with no methods
c) A class that only contains class variables
d) A class that is not inherited by any other class

Answer:

a) A class that cannot be instantiated and contains one or more abstract methods

Explanation:

An abstract class in Python is a class that cannot be instantiated on its own and contains one or more abstract methods. Abstract methods are methods declared in the abstract class but do not have any implementation. Subclasses of the abstract class must provide implementations for these abstract methods.

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 Dog class
dog = Dog()
print(dog.sound())  # Output: Bark

In this example, the Animal class is an abstract class with an abstract method sound(). The Dog class inherits from Animal and provides an implementation for the sound() method.

Abstract classes are useful for defining a common interface that must be implemented by all subclasses, ensuring a consistent design across different implementations.

Leave a Comment

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

Scroll to Top