面试题答案
一键面试import math
class Shape:
def area(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
shapes = [Rectangle(3, 4), Circle(5)]
for shape in shapes:
print(shape.area())
上述代码首先定义了基类Shape
,它有一个area
方法作为占位。Rectangle
类继承自Shape
,通过传入宽和高来计算面积。Circle
类同样继承自Shape
,通过半径来计算面积。最后通过一个列表存储不同形状的对象,并遍历调用area
方法来获取每个图形的面积。