Python 入門指南 5.0

exercise2007.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
"""模組 exercise2007
類別 Point
 方法 set_value()"""

# 定義座標類別
class Point:
    # 設定實體屬性
    def __init__(self, x: int, y: int):
        # 呼叫設定屬性的方法
        if not self.set_value(x, y):
            raise ValueError

     # 設定屬性的方法
    def set_value(self, x: int, y: int) -> bool:
        # 檢查參數是否為整數
        try:
            # 檢查參數 x 、 y 是否為整數
            assert type(x) is int
            assert type(y) is int
            # 設定實體屬性
            self.x = x
            self.y = y
            # 回傳 True
            return True
        except AssertionError:
            # 回傳 False
            return False

    # 設定字串形式
    def __str__(self):
        return "(" + str(self.x) +\
               ", " + str(self.y) + ")"

    # 設定布林屬性
    def __bool__(self):
        if self.x != None and self.y != None:
            return True
        else:
            return False

# 執行部分
if __name__ == "__main__":
    print(__doc__)

# 檔名: exercise2007.py
# 說明:《Python入門指南》的練習
# 網站: http://kaiching.org
# 作者: 張凱慶
# 時間: 2023 年 10 月

回到練習題目
上一頁 exercise2006.py
回 Python 入門指南 5.0 首頁
下一頁 exercise2008.py
回 Python 教材首頁
回程式語言教材首頁