简体   繁体   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

Two Classes.两班。 I have a new object in the parent class that gives attributes a value, and a calling method that displays them.我在父 class 中有一个新的 object ,它为属性提供一个值,以及一个显示它们的调用方法。 Then I create a child class in a separate file and inherit from the parent class.然后我在一个单独的文件中创建一个子 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

  

Then I create object for Excavator class and I call show_description ().然后我为挖掘机 class 创建 object 并调用 show_description ()。 When I run the Excavator class file, it will also show me the print of the Vehicle, (Volvo).当我运行挖掘机 class 文件时,它还会显示车辆(沃尔沃)的打印信息。 And my goal was to use the show_descriptipn () method - from Vehicle, only to display the new object (Hitachi) in the Excavator class.而我的目标是使用来自Vehicle的show_descriptipn()方法,只在挖掘机class中显示新的object(日立)。 So, by calling a method from the parent class, we will get the result of both classes?那么,通过调用父 class 的方法,我们会得到这两个类的结果吗? 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__": if __name__ == "__main__":

Vehicle.py车辆.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挖掘机.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.这样,如果您运行任何一个模块,它只会 output 中定义的if __name__ == "__main__":部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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