实战
题目
设计一个名为MyRectangle的矩形类来表示矩形。这个类包含:
(1) 左上角顶点的坐标:x,y
(2) 宽度和高度:width、height
(3) 构造方法:传入x,y,width,height。如果(x,y)不传则默认是0,如果width 和height不传,则默认是100.
(4) 定义一个getArea() 计算面积的方法
(5) 定义一个getPerimeter(),计算周长的方法
(6) 定义一个draw()方法,使用海龟绘图绘制出这个矩形
自己写的代码:
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):#计算面积方法
return self.width*self.height
def getPermete(self):#计算周长方法
return (self.width+self.height)*2
def draw(self):#绘制矩形
import turtle
turtle.penup()
turtle.goto(self.x,self.y)
turtle.down()
turtle.goto(self.x,-self.y-self.height)
turtle.goto(-self.x+self.width,-self.y-self.height)
turtle.goto(-self.x+self.width,self.y)
turtle.goto(self.x,self.y)
turtle.done()
s=MyRectangle()
print(s.getArea())
print(s.getPermete())
s.draw()
用大模型写的方法
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):
return self.width * self.height
def getPerimeter(self):
return 2 * (self.width + self.height)
def draw(self):
# 创建一个新的海龟绘图窗口
screen = turtle.Screen()
screen.bgcolor("white") # 设置背景色为白色
# 创建一个海龟对象
rect_turtle = turtle.Turtle()
rect_turtle.speed(1) # 设置绘图速度
rect_turtle.penup() # 提起笔,移动到指定位置
rect_turtle.goto(self.x, self.y) # 移动到矩形左上角位置
rect_turtle.pendown() # 放下笔,开始绘图
# 绘制矩形
for _ in range(2):
rect_turtle.forward(self.width) # 向前移动width
rect_turtle.right(90) # 右转90度
rect_turtle.forward(self.height) # 向前移动height
rect_turtle.right(90) # 右转90度
# 结束绘图
turtle.done()
# 示例:创建矩形对象并调用方法
rectangle = MyRectangle(50, 50, 200, 150)
print("Area:", rectangle.getArea())
print("Perimeter:", rectangle.getPerimeter())
rectangle.draw() # 这将打开一个新的窗口并绘制矩形