Python学习(十二)

本文介绍了如何在Python中设计一个名为MyRectangle的矩形类,包括坐标参数、默认值、计算面积和周长的方法,以及使用海龟绘图模块绘制矩形的实现过程。
摘要由CSDN通过智能技术生成

实战

题目
设计一个名为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()  # 这将打开一个新的窗口并绘制矩形
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_44006060

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值