两课。我在父类中有一个新对象,该对象为属性提供了一个值,并显示了它们的调用方法。然后,我在单独的文件中创建一个子类,并从父类继承。
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
然后,我为挖掘机类创建对象,并调用show_description()。当我运行Excavator类文件时,它还会向我显示Vehicle(Volvo)的打印。我的目标是使用Vehicle的show_descriptipn()方法,仅在Excavator类中显示新对象(Hitachi)。因此,通过从父类调用方法,我们将得到两个类的结果吗?我们继承了所有东西,甚至继承了创建的对象?或者在这种情况下我做错了什么,或者我听不懂。有人可以解释一下吗?
使用不 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()
挖掘机
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__":
节中定义的内容。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句