
abc 【抽象 Class】
簡介
What is abc?
How to Use abc?
from abc import ABC, abstractmethod
# Define an Abstract Base Class
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
# Implement Subclasses
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
def perimeter(self):
return 2 * (self.length + self.width)
# Create an instance of Rectangle
my_rectangle = Rectangle(3, 4)
# Calculate and print the area and perimeter
print("Rectangle Area: ", my_rectangle.area()) # Output: 12
print("Rectangle Perimeter: ", my_rectangle.perimeter()) # Output: 14Why Use abc?
When to Use abc?
Conclusion
Last updated