Skip to content

【练习】矩形面积和周长

项目简介

矩形面积和周长

知识模块

  • Python 编程语言

知识点

  • 静态方法
  • 函数返回值与参数处理

受众

  • 初级测试开发工程师
  • 初级Python开发工程师

作业要求

编写一个Python程序,创建一个几何图形计算程序,使用静态方法来计算矩形的面积和周长。

解题思路

  1. 创建一个几何图形计算类

  2. 使用 @staticmethod 装饰器定义静态方法

完整代码

class Geometry:
    @staticmethod
    def rectangle_area(width, height):
        return width * height

    @staticmethod
    def rectangle_P(width, height):
        return 2 * (width + height)


# 主程序
width = 4
height = 6
print(f"矩形的面积:{Geometry.rectangle_area(width, height)}")
print(f"矩形的周长:{Geometry.rectangle_P(width, height)}")

代码讲解

  1. 静态方法 rectangle_area@staticmethod 装饰器:这个装饰器用于将下面的 rectangle_area 方法定义为静态方法,即可以通过类名直接调用。

  2. def rectangle_area(width, height):这个静态方法用于计算矩形的面积。它接收 width(宽度)和 height(高度)作为参数,然后返回宽度乘以高度的结果,即矩形的面积。

  3. def rectangle_P(width, height):用于计算矩形的周长。

  4. 调用静态方法:使用类名 Geometry 和点号 . 来调用静态方法。

  5. Geometry.rectangle_area(width, height):调用静态方法 rectangle_area 来计算矩形的面积。