Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

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?

question from:https://stackoverflow.com/questions/65905032/parent-class-with-new-object-and-new-object-in-subclass-object-method-inherita

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...