What Is Abstraction in Python? How Is Abstraction Implemented in Python?
What Is Abstraction in Python? How Is Abstraction Implemented in Python?
Abstraction in Python
class Animal(ABC):
@abstractmethod
def talk(self):
pass
class Cat(Animal):
def talk(self):
return "Meow"
class Dog(Animal):
def talk(self):
return "Woof"
cat = Cat()
dog = Dog()
# Call the talk() method on each instance and print the result
Output
Meow
Woof
In this example, Animal is an abstract class with an abstract method
talk(). Cat and Dog are concrete subclasses of Animal that implement
the talk() method. By defining Animal as an abstract class, we can
ensure that all animals have a talk() method, without dictating how
that method should be implemented. This allows us to create more
flexible and extensible programs that can easily accommodate new
types of animals in the future.