python面向对象网络程序设计作业
题目
设计一个Rectangle类来表示矩形。这个类包括:
两个数据域width和height。
构造方法,创建一个指定width和height的矩形。将1作为width和height的默认值。
一个名为gerArea()的方法来返回这个矩形的面积。
一个名为getPerimeter()的方法来返回周长。
实现这个类。
编写一个测试程序创建一个Rectangle对象,宽为4高为40。显示这个矩形的宽、高、面积和周长。
运行结果如下:
The Rectangle's width is 4
The Rectangle's height is 40
The Rectangle's area is 160
The Rectangle's perimeter is 88
分析
这个作业也没啥难度,就是对python语法class的简单练习,直接上code
答案
class Rectangle:
def __init__(self, width=1, height=1):
self.width = width
self.height = height
def getArea(self):
return self.width * self.height
def getPerimeter(self):
return 2 * (self.width + self.height)
testRec = Rectangle(4, 40)
print("The Rectangle's width is %d" % testRec.width)
print("The Rectangle's height is %d" % testRec.height)
print("The Rectangle's area is %d" % testRec.getArea())
print("The Rectangle's perimeter is %d" % testRec.getPerimeter())
注意
提交作业时注意对齐就好