简体   繁体   中英

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

Two Classes. I have a new object in the parent class that gives attributes a value, and a calling method that displays them. Then I create a child class in a separate file and inherit from the parent 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

  

Then I create object for Excavator class and I call show_description (). When I run the Excavator class file, it will also show me the print of the Vehicle, (Volvo). And my goal was to use the show_descriptipn () method - from Vehicle, only to display the new object (Hitachi) in the Excavator class. So, by calling a method from the parent class, we will get the result of both classes? We inherit everything, even the created objects? Or maybe I am doing something wrong in this case, or I don`t understand something. Could someone explain this?

Use ole if __name__ == "__main__":

Vehicle.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()

Excavator.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()

This way, if you run either module it will only output what is defined in the if __name__ == "__main__": section.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM