Python 入門指南 5.0
exercise1811.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79 | # 引入標準程式中的 abc
import abc
# 引入 Point 定義
from exercise1810 import Point
# 定義父類別
class Animal:
# 設定實體屬性
def __init__(self, p: Point, n: str, c: str):
# 檢查參數
try:
# 確認參數型態
assert type(p) is Point
assert type(n) is str
assert type(c) is str
# 動物座標
self.point = p
# 動物種類
self.name = n
# 動物陣營
self.camp = c
except AssertionError:
raise ValueError
# 動物生命
self.health = True
# 設定字串形式
def __str__(self):
return self.name
# 設定布林屬性
def __bool__(self):
if self.health:
return True
else:
return False
# 向上移動
def up(self):
self.point.y += 1
# 向下移動
def down(self):
self.point.y -= 1
# 向右移動
def right(self):
self.point.x += 1
# 向左移動
def left(self):
self.point.x -= 1
# 定義過河的抽象方法
@abc.abstractmethod
def cross_river(self):
# 發起未實作的例外
raise NotImplemented
# 執行部分
if __name__ == "__main__":
try:
# 建立大象物件
elephant = Animal((2,1), "象", "Blue")
# 印出 elephant
print(elephant)
# 大象過河
elephant.cross_river()
except ValueError:
print("設定錯誤")
except:
print("大象不能過河")
# 檔名: exercise1811.py
# 說明:《Python入門指南》的練習
# 網站: http://kaiching.org
# 作者: 張凱慶
# 時間: 2023 年 10 月
|