天天看點

Day_5 python基礎知識第六章(1)_設計類

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