MST
星途 面试题库

面试题:Python类的继承与多态实现

假设有一个基类`Shape`,包含`area`方法用于计算图形面积,设计两个子类`Rectangle`和`Circle`继承自`Shape`,并重写`area`方法以实现各自面积的计算逻辑。同时,编写一段代码展示如何利用多态性,通过一个列表存储不同形状对象,并遍历该列表调用`area`方法获取每个图形的面积。
40.5万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
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方法来获取每个图形的面积。