高考申論題
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
- 逐行追蹤:Python 的繼承與
__init__比較直觀,但要注意子類別是否有呼叫super().__init__。在本題中,子類別完全覆蓋了__init__且沒呼叫父類別,這會導致父類別定義的某些屬性(如description)若沒在子類別賦值,則子類別實體可能沒有該屬性。 - 多型與覆蓋:注意
DoubleSquare覆蓋了perimeter,計算邏輯不同。Square繼承Shape但沒覆蓋area,故使用Shape的area。
🤖
AI 詳解
AI 專屬家教
【考點分析】 本題考察 Python 的類別繼承(Inheritance)、方法覆蓋(Method Overriding)、以及屬性初始化動態性。 【分析與論述】
▼ 還有更多解析內容