class Rectangle: 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)

class Square(Rectangle): def init(self, side): super().init(side, side)

def area(self):
    return self.length ** 2

def perimeter(self):
    return 4 * self.length

使用对象调用

r = Rectangle(5, 3) print("矩形面积为:", r.area()) print("矩形周长为:", r.perimeter())

s = Square(4) print("正方形面积为:", s.area()) print("正方形周长为:", s.perimeter())

3编程计算矩形的类构造函数初始化矩形的长和宽并使用方法计算面周长。通过对象调用。定义子类正方形利用构造函数初始化正方形边长计算面积和周长。

原文地址: https://www.cveoy.top/t/topic/bSw7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录