Python 入門指南 5.0
exercise1812.py
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 | # 引入 Point 定義
from exercise1810 import Point
# 引入 Animal 定義
from exercise1811 import Animal
# 定義 Lion
class Lion(Animal):
def __init__(self, p: Point, c: str):
# 檢查參數
try:
# 確認參數型態
assert type(p) is Point
assert type(c) is str
# 設定父類別
super().__init__(p, "獅", c)
except AssertionError:
raise ValueError
# 設定子類別屬性
self.food = ["獅", "虎", "豹", "狼", "狗", "貓", "鼠"]
# 實作抽象方法
def cross_river(self, d):
# 依據參數 d 進行移動
match d:
case "up":
self.point.y -= 4
case "down":
self.point.y += 4
case "right":
self.point.x += 3
case "left":
self.point.x -= 3
case _:
print("Something wrong!!")
# 執行部分
if __name__ == "__main__":
try:
# 建立 Lion 物件
lion = Lion(Point(3,3), "Blue")
# 印出獅子所在座標
print("動物" + lion.name + "在" + str(lion.point))
# 讓獅子過河
lion.cross_river("up")
# 印出獅子所在座標
print("動物" + lion.name + "在" + str(lion.point))
except ValueError:
print("設定錯誤")
# 檔名: exercise1812.py
# 說明:《Python入門指南》的練習
# 網站: http://kaiching.org
# 作者: 張凱慶
# 時間: 2023 年 10 月
|