admin 管理员组文章数量: 1087817
Python基础学习笔记——设计一个名为MyRectangle的矩形类来表示矩形
学习目标:
‘设计一个名为MyRectangle的矩形类来表示矩形,这个类包含:
(1)左上角坐标:x,y
(2)宽度和高度
(3)构造方法:传入x,y,width,height.如果(x,y)不传默认是0,
如果width和height不传,则默认是100.
(4)定义getArea()计算面积的方法
(5)d定义一个getPerimeter(),计算周长的方法
(6)定义一个draw()方法,使用海龟制图画出这个矩形’
解决方案代码:
class MyRectangle:def __init__(self, x, y, width, height): # 添加一个实例属性self.x = xself.y = yself.width = widthself.height = heightdef input(self):if self.x == ' ' and self.y == ' ':self.x = 0self.y = 0print("输入为x={0},y={1},width={2},height={3}".format(self.x, self.y, self.width, self.height))else:if self.width == ' ' and self.height == ' ':self.width = 100self.height = 100print("输入为x={0},y={1},width={2},height={3}".format(self.x, self.y, self.width, self.height))else:print("输入为x={0},y={1},width={2},height={3}".format(self.x, self.y, self.width, self.height))def getArea(self):Area = self.width * self.heightprint("该矩形的面积为:", Area)def getPerimeter(self):Perimeter = (self.width + self.height) * 2print("该矩形的周长为:", Perimeter)def draw(self):import turtle as t#import turtlet.screensize(self.width * 3, self.height * 3, 'black')t.pensize(3)t.speed(1)t.color('pink')t.goto(self.x, self.y)t.pendown()t.forward(self.width)t.right(90)t.forward(self.height)t.right(90)t.forward(self.width)t.home()print("制图完成!")t.done()t1 = MyRectangle(2, 2, 300, 200)
t1.input()
t1.getArea()
t1.getPerimeter()
t1.draw()
运行结果:
本篇文章问题来自高淇老师python400集课后习题.新手上路多多指正!
本文标签: Python基础学习笔记设计一个名为MyRectangle的矩形类来表示矩形
版权声明:本文标题:Python基础学习笔记——设计一个名为MyRectangle的矩形类来表示矩形 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/b/1694411431a251747.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论