Last active
April 28, 2024 08:50
-
-
Save 2tony2/08641bc1b93c7a03855f3aa064f5f8f7 to your computer and use it in GitHub Desktop.
Example of Python Abstract Base Class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from abc import ABC, abstractmethod | |
class Animal(ABC): | |
@abstractmethod | |
def make_sound(self): | |
"""Each subclass must implement a method to make a specific animal sound.""" | |
pass | |
@abstractmethod | |
def move(self): | |
"""Each subclass must implement a method to define how the animal moves.""" | |
pass | |
class Dog(Animal): | |
def make_sound(self): | |
return "Bark" | |
# The 'move' method is intentionally not implemented to demonstrate the error | |
class Fish(Animal): | |
def make_sound(self): | |
return "Blub" | |
def move(self): | |
return "Swims" | |
# Try to instantiate classes and use methods | |
if __name__ == "__main__": | |
try: | |
animal = Animal() # This will raise an error because Animal is abstract | |
except TypeError as e: | |
print("Error:", e) | |
try: | |
dog = Dog() # This will also raise an error because it does not implement all abstract methods | |
except TypeError as e: | |
print("Error:", e) | |
fish = Fish() # This will work fine | |
print("Fish:", fish.make_sound(), "and", fish.move()) | |
# Dog and Animal instantiation errors are shown in the output |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment