from abc import ABC, abstractmethod
# ---------------------------------------------------------
# بخش ۱ و ۳: تعریف کلاس پایه انتزاعی (Abstraction)
# ---------------------------------------------------------
class Animal(ABC):
# class attribute
total_animals = 0
def __init__(self, name, age):
# public attribute
self.name = name
# protected attribute
self._age = age
# private attribute
self.__health = 100
# Increase after create object
Animal.total_animals += 1
# getter
@property
def health(self):
return self.__health
# setter
@health.setter
def health(self, value):
if not 0 <= value <= 100:
raise ValueError(
"Health must be between 0 and 100"
)
self.__health = value
@abstractmethod
def make_sound(self):
pass
@classmethod
def get_total_animals(cls):
return cls.total_animals
@staticmethod
def is_valid_age(age):
return age > 0
def __str__(self):
return f"{self.name} ({self.__class__.__name__}),"
"age: {self._age},"
"health: {self.__health}"
def __eq__(self, other):
return self.name == other.name
# ---------------------------------------------------------
# بخش ۲: وراثت - هر کلاس فرزند، Animal رو گسترش میده
# ---------------------------------------------------------
class Lion(Animal):
def make_sound(self):
print(f"{self.name} says: Roar!")
class Parrot(Animal):
def __init__(self, name, age, can_talk=True):
super().__init__(name, age)
self.can_talk = can_talk
def make_sound(self):
if self.can_talk:
print(f"{self.name} says: Hello!")
else:
print(f"{self.name} says: Squawk!")
class Elephant(Animal):
def make_sound(self):
print(f"{self.name} says: Pawoo!")
# ---------------------------------------------------------
# کلاسی که مجموعهای از حیوانات رو نگه میداره
# ---------------------------------------------------------
class Zoo:
def __init__(self, name):
self.name = name
self.animals = []
def add_animal(self, animal):
self.animals.append(animal)
def __len__(self):
return len(self.animals)
def make_all_sounds(self):
for animal in self.animals:
animal.make_sound()
# ---------------------------------------------------------
# اجرای برنامه (Demo)
# ---------------------------------------------------------
if __name__ == "__main__":
zoo = Zoo("Sari Zoo")
lion = Lion("Simba", 5)
parrot = Parrot("Polly", 2, can_talk=True)
elephant = Elephant("Dumbo", 8)
zoo.add_animal(lion)
zoo.add_animal(parrot)
zoo.add_animal(elephant)
print("--- __str__ ---")
for a in zoo.animals:
print(a)
print("\n--- Polymorphism ---")
zoo.make_all_sounds()
print("\n--- Encapsulation ---")
lion.health = 80
print(f"سلامت {lion.name}: {lion.health}")
try:
# Invalid value => Error
lion.health = 150
except ValueError as e:
print("Error:", e)
print("\n--- Private Variable ---")
try:
print(lion.__health)
except AttributeError as e:
print("Error:", e)
print("\n--- Class Method ---")
print("Total Animal:", Animal.get_total_animals())
print("Length (__len__):", len(zoo))
print("\n--- Static Method ---")
print(Animal.is_valid_age(5))
print(Animal.is_valid_age(-3))
print("\n--- Abstract Object ---")
try:
a = Animal("X", 1)
except TypeError as e:
print("Error:", e)
print("\n--- (__eq__) ---")
lion2 = Lion("Simba", 5)
print(lion == lion2)
class RobotAnimal:
def __init__(self, name):
self.name = name
def make_sound(self):
print(f"{self.name} says: Beep Boop!")
zoo.add_animal(RobotAnimal("R2D2"))
zoo.make_all_sounds()