第九章第一题(Rectangle类)(Rectangle class)

第九章第一题(Rectangle类)(Rectangle class)

  • 9.1(Rectangle类)遵照9.2节中 Circle 类的例子,设计一个名为 Rectangle 的类表示矩形。
    这个类包括:

    • 两个名为 width 和 height 的 double 型数据域,它们分别表示矩形的宽和高。width 和 height 的默认- 值都为1。
    • 一个创建默认矩形的无参构造方法。
    • 一个创建 width 和 height 为指定值的矩形的构造方法。
    • 一个名为 getArea() 的方法返回这个矩形的面积。
    • 一个名为 getPerimeter() 的方法返回周长。

    画出该矩形的 UML 图并实现这个类。编写一个测试程序,创建两个 Rectangle 对象——一个矩形的宽为 4 而高为 40,另一个矩形的宽为 3.5 而高为 35.9 。按照这个顺序显示每个矩形的宽、高、面积、周长。

  • 9.1(rectangle class) following the example of circle class in Section 9.2, design a class named rectangle to represent rectangle.
    This class includes:

    • Two double data fields named width and height represent the width and height of the rectangle, respectively. The default values for width and height are 1.
    • A nonparametric construction method for creating default rectangles.
    • A construction method for creating a rectangle with the specified values of width and height.
    • A method called getarea() returns the area of the rectangle.
    • A method called getperimeter () returns the perimeter.

    Draw a UML diagram of the rectangle and implement the class. Write a test program and create two rectangle objects - one rectangle is 4 in width and 40 in height, and the other is 3.5 in width and 35.9 in height. Display the width, height, area, perimeter of each rectangle in this order.

  • 参考代码:

package chapter09
针对Python教程第九章作业的内容及答案,虽然具体参考资料未直接提供相关内容,但可以根据常见的Python教材结构推测该章节可能覆盖的主。通常情况下,Python教程的第九章可能会深入探讨面向对象编程(OOP),包括(class)、实例(instance)、继承(inheritance)以及多态(polymorphism)[^1]。 ### Python 教程 第九章 作业 内容 #### 定义与实例化 编写一个名为`Rectangle`的来表示矩形。这个应该有两个属性:长度(`length`)和宽度(`width`)。创建两个方法用于计算面积(`get_area()`)和周长(`get_perimeter()`)。 ```python class Rectangle: def __init__(self, length, width): self.length = length self.width = width def get_area(self): return self.length * self.width def get_perimeter(self): return 2 * (self.length + self.width) rect = Rectangle(4, 5) print(f'Area: {rect.get_area()}') # Area: 20 print(f'Perimeter: {rect.get_perimeter()}') # Perimeter: 18 ``` #### 继承机制的应用 设计一个基`Shape`及其子`Circle`。`Shape`应有一个抽象的方法`area()`,而`Circle`则实现此方法并接受半径作为参数以计算圆的面积。 ```python from abc import ABC, abstractmethod import math class Shape(ABC): @abstractmethod def area(self): pass class Circle(Shape): def __init__(self, radius): super().__init__() self.radius = radius def area(self): return math.pi * pow(self.radius, 2) circle = Circle(3) print(f'Circle Area: {circle.area():.2f}') # Circle Area: 28.27 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值