面试题答案
一键面试class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def calculate_area(self):
return self.length * self.width
def calculate_perimeter(self):
return 2 * (self.length + self.width)
代码逻辑说明:
- 类定义:定义了一个名为
Rectangle
的类,用于表示矩形。 - 初始化方法
__init__
:接受length
(长)和width
(宽)作为参数,并将它们赋值给对象的属性self.length
和self.width
,用于初始化矩形的长和宽。 - 计算面积方法
calculate_area
:通过返回self.length * self.width
来计算矩形的面积。 - 计算周长方法
calculate_perimeter
:通过返回2 * (self.length + self.width)
来计算矩形的周长。