2025年3月24日 星期一

用繪圖來學習Python物件導向設計以及意外處理

類別階層圖:





功能:draw()
以下程式是由ChatGPT產生。

範例一
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import turtle

class Shape:
    def __init__(self, x, y, color):
        self.x = x
        self.y = y
        self.color = color
        self.t = turtle.Turtle()
        self.t.speed(3)
        self.t.penup()
        self.t.goto(self.x, self.y)
        self.t.pendown()
        self.t.color(self.color)

    def draw(self):
        pass  # 讓子類別實作

class Square(Shape):
    def __init__(self, x, y, color, side_length):
        super().__init__(x, y, color)
        self.side_length = side_length

    def draw(self):
        for _ in range(4):
            self.t.forward(self.side_length)
            self.t.right(90)

class CircleShape(Shape):
    def __init__(self, x, y, color, radius):
        super().__init__(x, y, color)
        self.radius = radius

    def draw(self):
        self.t.circle(self.radius)

# 初始化 turtle 畫布
screen = turtle.Screen()
screen.bgcolor("white")

# 創建方形與圓形物件
square = Square(-50, 50, "blue", 100)
circle = CircleShape(100, -50, "red", 50)

# 繪製圖形
square.draw()
circle.draw()

# 點擊畫布後關閉
screen.exitonclick()

執行結果:

範例二

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import turtle

class Shape:
    def __init__(self, x, y, color):
        try:
            if not isinstance(x, (int, float)) or not isinstance(y, (int, float)):
                raise ValueError("座標 (x, y) 必須是數字")
            if not isinstance(color, str):
                raise TypeError("顏色必須是字串")
            
            self.x = x
            self.y = y
            self.color = color
            self.t = turtle.Turtle()
            self.t.speed(3)
            self.t.penup()
            self.t.goto(self.x, self.y)
            self.t.pendown()
            self.t.color(self.color)
        except Exception as e:
            print(f"初始化 Shape 物件時發生錯誤: {e}")

    def draw(self):
        pass  # 讓子類別實作

class Square(Shape):
    def __init__(self, x, y, color, side_length):
        try:
            super().__init__(x, y, color)
            if not isinstance(side_length, (int, float)) or side_length <= 0:
                raise ValueError("邊長必須是正數")
            self.side_length = side_length
        except Exception as e:
            print(f"初始化 Square 物件時發生錯誤: {e}")

    def draw(self):
        try:
            for _ in range(4):
                self.t.forward(self.side_length)
                self.t.right(90)
        except AttributeError:
            print("無法繪製正方形,請檢查初始化是否成功")

class CircleShape(Shape):
    def __init__(self, x, y, color, radius):
        try:
            super().__init__(x, y, color)
            if not isinstance(radius, (int, float)) or radius <= 0:
                raise ValueError("半徑必須是正數")
            self.radius = radius
        except Exception as e:
            print(f"初始化 CircleShape 物件時發生錯誤: {e}")

    def draw(self):
        try:
            self.t.circle(self.radius)
        except AttributeError:
            print("無法繪製圓形,請檢查初始化是否成功")

# 初始化 turtle 畫布
screen = turtle.Screen()
screen.bgcolor("white")

# 測試輸入錯誤的數據
invalid_square = Square("wrong", 50, "blue", -100)  # 會觸發 ValueError
invalid_circle = CircleShape(100, -50, 123, 50)  # 會觸發 TypeError

# 創建正常的方形與圓形物件
square = Square(-50, 50, "blue", 100)
circle = CircleShape(100, -50, "red", 50)

# 繪製圖形
square.draw()
circle.draw()

# 點擊畫布後關閉
screen.exitonclick()

執行結果:
初始化 Shape 物件時發生錯誤: 座標 (x, y) 必須是數字
初始化 Square 物件時發生錯誤: 邊長必須是正數
初始化 Shape 物件時發生錯誤: 顏色必須是字串



沒有留言:

張貼留言