将教材例题6.8改写,分别用抽象方法和接口回调两种形式来实现多态
时间: 2023-08-15 18:14:18 浏览: 99
教材例题6.8原题为:
定义一个图形类,包括一个面积计算方法和一个图形名称属性。然后派生出矩形类、三角形类和圆形类,分别实现它们的面积计算方法。最后编写一个函数,接受一个图形对象列表作为参数,遍历列表并调用每个图形对象的面积计算方法,返回所有图形的总面积。
以下是使用抽象方法实现多态的代码:
```python
from abc import ABC, abstractmethod
from math import pi
class Shape(ABC):
def __init__(self, name):
self.name = name
@abstractmethod
def area(self):
pass
class Rectangle(Shape):
def __init__(self, name, width, height):
super().__init__(name)
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Triangle(Shape):
def __init__(self, name, base, height):
super().__init__(name)
self.base = base
self.height = height
def area(self):
return 0.5 * self.base * self.height
class Circle(Shape):
def __init__(self, name, radius):
super().__init__(name)
self.radius = radius
def area(self):
return pi * self.radius ** 2
def total_area(shapes):
total = 0
for shape in shapes:
total += shape.area()
return total
shapes = [
Rectangle("Rectangle", 2, 3),
Triangle("Triangle", 2, 3),
Circle("Circle", 1)
]
print(total_area(shapes)) # 输出:10.141592653589793
```
以下是使用接口回调实现多态的代码:
```python
from math import pi
class Shape:
def __init__(self, name):
self.name = name
def area(self):
pass
class Rectangle(Shape):
def __init__(self, name, width, height):
super().__init__(name)
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Triangle(Shape):
def __init__(self, name, base, height):
super().__init__(name)
self.base = base
self.height = height
def area(self):
return 0.5 * self.base * self.height
class Circle(Shape):
def __init__(self, name, radius):
super().__init__(name)
self.radius = radius
def area(self):
return pi * self.radius ** 2
def total_area(shapes):
total = 0
for shape in shapes:
if isinstance(shape, Shape):
total += shape.area()
return total
shapes = [
Rectangle("Rectangle", 2, 3),
Triangle("Triangle", 2, 3),
Circle("Circle", 1)
]
print(total_area(shapes)) # 输出:10.141592653589793
```
这两种方式都可以实现多态,不同之处在于抽象方法方式需要继承抽象类,并且必须实现抽象方法,而接口回调则是通过判断对象类型来调用相应的方法。
阅读全文