Python 抽象类和抽象方法
Python 通过继承 abc 模块中的 ABC 来实现抽象类,通过 abc 模块的 abstractmethod 装饰抽象方法
示例
from enum import Enum
from abc import ABC, abstractmethod
class ShapeType(Enum):
RECTANGLE = 1
SQUARE = 2
class Shape(ABC):
def __init__(self, t: ShapeType):
self.type = t
def get_area(self):
raise NotImplementedError
def __str__(self):
return f"I'm a {self.type.name.lower()}, my area is {self.get_area()}"
class Rectangle(Shape):
def __init__(self, width: int, height: int):
super().__init__(ShapeType.RECTANGLE)
self.width = width
self.height = height
def get_area(self):
return self.width * self.height
class Square(Shape):
def __init__(self, side_length: int):
super().__init__(ShapeType.SQUARE)
self.side_length = side_length
def get_area(self):
return self.side_length * self.side_length
def test_abstract_class():
shapes = [Rectangle(2, 3), Square(5), Rectangle(3, 4)]
for shape in shapes:
print(f"{shape}")
标签:__,Python,self,init,length,抽象,抽象类,class,def
From: https://www.cnblogs.com/goallin/p/17642135.html