簡體   English   中英

Parent Class with new object, and new object in Subclass, object/method inheritance Python

[英]Parent Class with new object, and new object in Subclass, object/method inheritance Python

兩班。 我在父 class 中有一個新的 object ,它為屬性提供一個值,以及一個顯示它們的調用方法。 然后我在一個單獨的文件中創建一個子 class 並從父 class 繼承。

 class Vehicle:

    def __init__(self, brand, model):   

        self.brand = brand 
        self.model = model 

    def show_description(self):
        print('Brand: ', self.brand, 'Model: ', self.model)

volvo = Vehicle('Volvo','L350H') 
volvo.show_description()  



#new class in separate file:
# ps. import not correct?

from vehicle import vehicle

class Excavator(Vehicle):
    
    def __init__(self, brand, model):
        super.__init__(brand, model)


hitachi = Excavator('Hitachi','EX8000')
hitachi.show_description()


Output: Brnad: Volvo Model: L350H
        Brand: Hitachi Model: EX8000

  

然后我為挖掘機 class 創建 object 並調用 show_description ()。 當我運行挖掘機 class 文件時,它還會顯示車輛(沃爾沃)的打印信息。 而我的目標是使用來自Vehicle的show_descriptipn()方法,只在挖掘機class中顯示新的object(日立)。 那么,通過調用父 class 的方法,我們會得到這兩個類的結果嗎? 我們繼承一切,甚至是創建的對象? 或者在這種情況下我做錯了什么,或者我不明白什么。 有人可以解釋一下嗎?

if __name__ == "__main__":

車輛.py

class Vehicle:

    def __init__(self, brand, model):   

        self.brand = brand 
        self.model = model 

    def show_description(self):
        print('Brand: ', self.brand, 'Model: ', self.model)
if __name__ == "__main__":
  volvo = Vehicle('Volvo','L350H') 
  volvo.show_description()

挖掘機.py

from Vehicle import Vehicle

class Excavator(Vehicle):
    
    def __init__(self, brand, model):
        super.__init__(brand, model)

if __name__ == "__main__":
  hitachi = Excavator('Hitachi','EX8000')
  hitachi.show_description()

這樣,如果您運行任何一個模塊,它只會 output 中定義的if __name__ == "__main__":部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM