突然想到 在 python 如何新增一個類別與繼承一個類別?

可以參考以下註解程式碼:

 

 

# 宣告 原本類別
class TestClass:
    def __init__(self, attribute=""):
        self.attribute = attribute
    def method(self):
        print("attribute = ", self.attribute)

# 宣告 新類別
class ChildTestClass(TestClass):
    def __init__(self, attribute, new_attribute):
        # 針對父類別初始化 
        # 如果沒有這段,則會只有繼承函式,少了初始化參數,也就是 self.attribute = attribute 這一段
        super().__init__(attribute)
        self.new_attribute = new_attribute

    def child_method(self):
        print("attribute = ", self.attribute)
        print("new_attribute = ", self.new_attribute)

# 初始化 新類別 ,指定初始值
TestObj = ChildTestClass(attribute="attribute text", new_attribute="new_attribute")
# 呼叫類別中的函式
TestObj.child_method()
# attribute =  attribute text 
# new_attribute =  new_attribute

 

其實在 python 這樣的繼承方式已經算非常簡單了

而且非常直覺

我想這也是 python 的賣點