Python 入門指南 5.0
exercise2903.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 | # 引入 Point 定義
from exercise1810 import Point
# 引入 Animal 定義
from exercise1811 import Animal
# 定義 Mouse
class Mouse(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):
print("老鼠不能過河")
# 執行部分
if __name__ == "__main__":
try:
# 建立 Mouse 物件
mouse = Mouse(Point(3,3), "Blue")
# 印出老鼠所在座標
print(f"動物{mouse.name}在 {mouse.point}")
# 讓老鼠往上移動
mouse.up()
# 印出老鼠所在座標
print(f"動物{mouse.name}在 {mouse.point}")
except ValueError:
print("設定錯誤")
# 檔名: exercise2903.py
# 說明:《Python入門指南》的練習
# 網站: http://kaiching.org
# 作者: 張凱慶
# 時間: 2023 年 11 月
|