【问题标题】:Parent Class with new object, and new object in Subclass, object/method inheritance Python具有新对象的父类,子类中的新对象,对象/方法继承Python
【发布时间】:2021-01-26 16:16:49
【问题描述】:

两个班。我在父类中有一个新对象,它给属性一个值,以及一个显示它们的调用方法。然后我在一个单独的文件中创建一个子类并从父类继承。

 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

  

然后我为 Excavator 类创建对象并调用 show_description()。当我运行 Excavator 类文件时,它还会显示车辆(沃尔沃)的打印。而我的目标是使用来自 Vehicle 的 show_descriptipn() 方法,仅在 Excavator 类中显示新对象(Hitachi)。那么,通过调用父类的方法,我们会得到两个类的结果吗?我们继承一切,甚至是创建的对象?或者在这种情况下我做错了什么,或者我不明白什么。有人可以解释一下吗?

【问题讨论】:

  • "那么,通过调用父类的方法,我们会得到两个类的结果?"不,因为您import 模块,它执行模块。在模块中,你做volvo.show_description(),所以当然输出Brnad: Volvo Model: L350H
  • 当你导入一个文件时,整个文件都会被执行——包括volvo的创建和打印它的描述,在你的情况下。
  • 顺便说一句,对模块使用小写名称,而不是大写。另请注意,您没有在类中创建对象
  • @simply_red 这与继承无关。什么都没有。同样,这是因为你写了volvo.show_description()。所以当然当你运行那个模块时,它会volvo.show_description()

标签: python class inheritance


【解决方案1】:

使用 oleif __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()

挖掘机.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()

这样,如果您运行任一模块,它只会输出if __name__ == "__main__": 部分中定义的内容。

【讨论】:

  • 原来我必须在我的情况下应用这个方法,直到我找到另一个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-06
  • 1970-01-01
  • 1970-01-01
  • 2021-11-25
  • 1970-01-01
相关资源
最近更新 更多