Day_5 python基础知识第六章(1)_设计类

本文主要探讨Python编程中的类设计,包括类的定义、属性和方法的使用,以及面向对象编程的基本概念。通过学习,读者将能掌握创建和使用Python类的基础知识。
摘要由CSDN通过智能技术生成

(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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值