2025年4月5日 星期六

USR教材:用水井三寶設計python類別


參考資料:水井姻緣花1

用水井三寶做為提問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
# 定義一個基礎寶物類別
class Treasure:
    def __init__(self, name, meaning, age):
        self.name = name
        self.meaning = meaning
        self.age = age

    def describe(self):
        return f"{self.name}:象徵 {self.meaning},已有 {self.age} 年歷史。"

    def __str__(self):
        return self.describe()

# 三寶:烏龜、白馬、番花

class Turtle(Treasure):
    def __init__(self):
        super().__init__("烏龜", "風水與守護", 300)

class WhiteHorse(Treasure):
    def __init__(self):
        super().__init__("白馬", "信仰與傳說", 150)

class Frangipani(Treasure):  # 雞蛋花的英文名稱
    def __init__(self):
        super().__init__("番花", "歷史與生命", 300)

# 建立物件
turtle = Turtle()
horse = WhiteHorse()
flower = Frangipani()

# 顯示介紹(透過 print(object) 直接呼叫 __str__)
print(turtle)
print(horse)
print(flower)

執行結果:
烏龜:象徵 風水與守護,已有 300 年歷史。
白馬:象徵 信仰與傳說,已有 150 年歷史。
番花:象徵 歷史與生命,已有 300 年歷史。

註:這些歷史時間只是ChatGPT對程式的預設值,需要再考證。

沒有留言:

張貼留言