Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...