免費開始練習
高考申論題 108年 [資訊處理] 程式語言

第 四 題

下列 Python 程式的執行結果為何?(15 分)
class Shape:
def __init__(self, x, y):
self.x = x
self.y = y
self.description = "unknown"
def area(self):
return self.x * self.y
def perimeter(self):
return 2 * self.x + 2 * self.y
def describe(self, text):
self.description = text

class Square(Shape):
def __init__(self, x):
self.x = x
self.y = x

class DoubleSquare(Square):
def __init__(self, y):
self.x = 2 * y
self.y = y
def perimeter(self):
return 2 * self.x + 3 * self.y

rectangle = Shape(100, 45)
print(rectangle.perimeter())

dictionary = {}
dictionary["DoubleSquare"] = DoubleSquare(5)
dictionary["Rectangle"] = Shape(600,45)
dictionary["Square"] = Square(20)
print(dictionary["Square"].area())

dictionary["DoubleSquare"].describe("Double square")
print(dictionary["Rectangle"].description)
📝 此題為申論題

思路引導 VIP

  1. 逐行追蹤:Python 的繼承與 __init__ 比較直觀,但要注意子類別是否有呼叫 super().__init__。在本題中,子類別完全覆蓋了 __init__ 且沒呼叫父類別,這會導致父類別定義的某些屬性(如 description)若沒在子類別賦值,則子類別實體可能沒有該屬性。
  2. 多型與覆蓋:注意 DoubleSquare 覆蓋了 perimeter,計算邏輯不同。Square 繼承 Shape 但沒覆蓋 area,故使用 Shapearea
🤖
AI 詳解 AI 專屬家教

【考點分析】 本題考察 Python 的類別繼承(Inheritance)、方法覆蓋(Method Overriding)、以及屬性初始化動態性。 【分析與論述】

▼ 還有更多解析內容

🏷️ 相關主題

物件導向程式設計:類別、方法與資料結構
查看更多「[資訊處理] 程式語言」的主題分類考古題

📝 同份考卷的其他題目

查看 108年[資訊處理] 程式語言 全題