[英]Parent Class with new object, and new object in Subclass, object/method inheritance Python
两班。 我在父 class 中有一个新的 object ,它为属性提供一个值,以及一个显示它们的调用方法。 然后我在一个单独的文件中创建一个子 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
然后我为挖掘机 class 创建 object 并调用 show_description ()。 当我运行挖掘机 class 文件时,它还会显示车辆(沃尔沃)的打印信息。 而我的目标是使用来自Vehicle的show_descriptipn()方法,只在挖掘机class中显示新的object(日立)。 那么,通过调用父 class 的方法,我们会得到这两个类的结果吗? 我们继承一切,甚至是创建的对象? 或者在这种情况下我做错了什么,或者我不明白什么。 有人可以解释一下吗?
if __name__ == "__main__":
车辆.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()
这样,如果您运行任何一个模块,它只会 output 中定义的if __name__ == "__main__":
部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.