(1)
设计一个名为 MyRectangle 的矩形类来表示矩形。这个类包含:
(1) 左上角顶点的坐标:x,y
(2) 宽度和高度:width、height
(3) 构造方法:传入 x,y,width,height。如果(x,y)不传则默认是 0,如果 width
和 height 不传,则默认是 100.
(4) 定义一个 getArea() 计算面积的方法
(5) 定义一个 getPerimeter(),计算周长的方法
(6) 定义一个 draw()方法,使用海龟绘图绘制出这个矩形
// An highlighted block
import turtle
class MyRectangle:
"""这个类是用来计算矩形面积、周长,以及绘制矩形用的"""
def __init__(self, x=0, y=0, width=100, height=100):
self.__x = x
self.__y = y
self.__width = width
self.__height = height
def getArea(self):
s = self.__width * self.__height
return s
def getPerimeter(self):
c = (self.__width + self.__height)*2
return c
def draw(self):
t = turtle.Pen()
t.penup()
t.goto(self.__x, self.__y)
t.pendown()
t.goto(self.__x + self.__width, self.__y)
t.goto(self.__x + self.__width, self.__y - self.__height)
t.goto(self.__x, self.__y - self.__height)
t.goto(self.__x, self.__y)
t.hideturtle()
turtle.done()
a = input("请输入坐标,中间用逗号隔开")
b = input("请输入宽和高,中间用逗号隔开")
attr1 = '('+a+')'
attr2 = '('+b+')'
rea1 = eval(attr1)
rea2 = eval(attr2)
x = int(rea1[0])
y = int(rea1[1])
width = int(rea2[0])
height = int(rea2[1])
myre1 = MyRectangle(x, y, width, height)
print("该矩形的面积为{}".format(myre1.getArea()))
print("该矩形的周长为{}".format(myre1.getPerimeter()))
myre1.draw()