from abc import ABC, abstractmethodclassPolygon(ABC):def__init__(self,sides):super().__init__() self.sides = sides@abstractmethoddefarea(self):"""Verification of side length"""ifnotall(i >0for i in self.sides):raiseValueError("All side lengths must be positive")classRectangle(Polygon):def__init__(self,sides):super().__init__(sides)defarea(self):super().area()# Calculate rectangle areareturn self.sides[0]* self.sides[1]classTriangle(Polygon):def__init__(self,sides):super().__init__(sides)defarea(self):super().area()# Calculate Heron's formula s =sum(self.sides)/2return (s * (s - self.sides[0]) * (s - self.sides[1]) * (s - self.sides[2])) **0.5print(Rectangle([5, 10]).area())# Output: 50print(Triangle([20, 10, 15]).area())# Output: 72.618
範例 – 影像處理
PYTHON
from abc import ABC, abstractmethodfrom PIL import ImageclassImageProcessor(ABC):def__init__(self,image_path):super().__init__() self.image = Image.open(image_path)@abstractmethoddefprocess(self):if self.image.mode !='RGB':raiseValueError("Image mode must be RGB")classImageResizer(ImageProcessor):def__init__(self,image_path,size):super().__init__(image_path) self.size = sizedefprocess(self):super().process()# Resize the imagereturn self.image.resize(self.size)classImageRotator(ImageProcessor):def__init__(self,image_path,angle):super().__init__(image_path) self.angle = angledefprocess(self):super().process()# Rotate the imagereturn self.image.rotate(self.angle)resizer =ImageResizer('image.jpg', (800, 800))resized_image = resizer.process()resized_image.save('resized_image.jpg')rotator =ImageRotator('image.jpg', 90)rotated_image = rotator.process()rotated_image.save('rotated_image.jpg')