python/animal_talk.py

75 lines
2.9 KiB
Python

"""
This module defines an abstract base class `Animal` and its subclasses `Dog` and `Cat`,
demonstrating object-oriented principles such as inheritance, abstraction, and polymorphism.
Classes:
Animal:
Abstract base class representing a generic animal.
Methods:
speak(): Abstract method to be implemented by subclasses for animal sound.
move(): Abstract method to be implemented by subclasses for animal movement.
Dog(Animal):
Represents a dog with breed, name, and age attributes.
Methods:
speak(): Returns the sound a dog makes ("Woof!").
move(): Returns a description of how a dog moves ("runs energetically").
Cat(Animal):
Represents a cat with breed, name, age, and color attributes.
Methods:
speak(): Returns the sound a cat makes ("Meow!").
move(): Returns a description of how a cat moves ("walks gracefully").
Usage:
Demonstrates polymorphism by creating instances of Dog and Cat and invoking their
respective speak and move methods.
"""
class Animal: # Abstract Base Class (Not to be instantiated directly)
def __init__(self):
pass
def speak(self):
raise NotImplementedError("Subclasses must implement this method")
def move(self):
raise NotImplementedError("Subclasses must implement this method")
class Dog(Animal): # Subclass of Animal with 3 attributes
def __init__(self, breed, name, age):
super().__init__()
self.breed = breed
self.name = name
self.age = age
def speak(self): # Implementation of abstract method
return "Woof!"
def move(self): # Implementation of abstract method
return "runs energetically"
class Cat(Animal): # Subclass of Animal with 4 attributes
def __init__(self, breed, name, age, color):
super().__init__()
self.breed = breed
self.name = name
self.age = age
self.color = color
def speak(self): # Implementation of abstract method
return "Meow!"
def move(self): # Implementation of abstract method
return "walks gracefully"
# Creating instances of Dog and Cat
my_dog = Dog("Collie","Buddy", 9)
my_cat = Cat("Simese","Whiskers", 3, "White")
my_other_dog = Dog("Snouser","Max", 5)
# Demonstrating polymorphism
print(f"My {my_dog.breed} dog, {my_dog.name}, age {my_dog.age} says {my_dog.speak()} and {my_dog.move()}")
print(f"My {my_cat.color} {my_cat.breed} cat, {my_cat.name}, age {my_cat.age} says {my_cat.speak()} and {my_cat.move()}")
print(f"My {my_other_dog.breed} dog, {my_other_dog.name}, age {my_other_dog.age} says {my_other_dog.speak()} and {my_other_dog.move()}")