阿摩線上測驗 登入

申論題資訊

試卷:105年 - 105 鐵路特種考試_高員三級_資訊處理:程式語言#53487
科目:程式語言
年份:105年
排序:0

申論題內容

一、物件導向語言中有所謂 overloading 的方法及建構子(constructor),請舉例並說明之。 (20 分)

詳解 (共 1 筆)

詳解 提供者:hchungw
在物件導向程式設計中,overloading(多載)是指在同一個類別中允許多個同名的方法或建構子存在,但它們的參數列表必須不同。Python 語言本身不支援傳統意義上的多載,但可以通過使用可變參數(*args 和 **kwargs)來實現相似的功能。
方法多載(Method Overloading)
在 Python 中,雖然不支援直接的多載,但可以通過檢查參數來模擬多載的行為。
範例(以 Python 為例)
python
複製程式碼
class MyClass:
    def display(self, *args):
        if len(args) == 1 and isinstance(args[0], int):
            print(f"Integer value: {args[0]}")
        elif len(args) == 2 and all(isinstance(arg, int) for arg in args):
            print(f"Two integer values: {args[0]}, {args[1]}")
        elif len(args) == 1 and isinstance(args[0], float):
            print(f"Double value: {args[0]}")
        elif len(args) == 1 and isinstance(args[0], str):
            print(f"String value: {args[0]}")
        else:
            print("Unsupported type or number of arguments")
# 使用示例
obj = MyClass()
obj.display(10)             # Integer value: 10
obj.display(10, 20)         # Two integer values: 10, 20
obj.display(10.5)           # Double value: 10.5
obj.display("Hello")        # String value: Hello
建構子多載(Constructor Overloading)
Python 中沒有傳統意義上的建構子多載,但可以使用 __init__ 方法和可變參數來實現類似的效果。
範例(以 Python 為例)
python
複製程式碼
class MyClass:
    def __init__(self, *args):
        if len(args) == 1 and isinstance(args[0], int):
            self.value = args[0]
            print(f"Initialized with integer: {self.value}")
        elif len(args) == 2 and all(isinstance(arg, int) for arg in args):
            self.value1, self.value2 = args
            print(f"Initialized with two integers: {self.value1}, {self.value2}")
        elif len(args) == 1 and isinstance(args[0], float):
            self.value = args[0]
            print(f"Initialized with float: {self.value}")
        elif len(args) == 1 and isinstance(args[0], str):
            self.value = args[0]
            print(f"Initialized with string: {self.value}")
        else:
            print("Unsupported type or number of arguments")
# 使用示例
obj1 = MyClass(10)          # Initialized with integer: 10
obj2 = MyClass(10, 20)      # Initialized with two integers: 10, 20
obj3 = MyClass(10.5)        # Initialized with float: 10.5
obj4 = MyClass("Hello")     # Initialized with string: Hello
總結
方法多載(Method Overloading): 通過檢查參數的數量和型別來模擬多載行為。
建構子多載(Constructor Overloading): 使用 __init__ 方法和可變參數來實現多種初始化方法。
這種方法提供了靈活性,可以根據不同的參數來執行不同的操作,模擬了多載的效果。