所以基本上我在 init ()中有一个带有一些参数的父类,现在我想定义一个子类,我想重新定义 init ()in子类只是在其中附加一个新参数。有没有方便的方法来完成这个?
这是我的代码:
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
def display_car(self):
#print "This is a "+self.color+" "+self.model+" with "+str(self.mpg)+" MPG."
print self.condition
def drive_car(self):
self.condition = "used"
class ElectricCar(Car):
def __init__(self, model, color, mpg,battery_type):
self.model = model
self.color = color
self.mpg = mpg
self.battery_type = battery_type
my_car = Car("DeLorean", "silver", 88)
my_car = ElectricCar("Fuck me","Gold",998,"molten salt")
print my_car.condition
my_car.drive_car()
print my_car.condition
新参数为battery_type
答案 0 :(得分:2)
您可以使用super()
访问父类' __init__()
让父母初始化其属性。示例 -
class ElectricCar(Car):
def __init__(self, model, color, mpg,battery_type):
super(ElectricCar, self).__init__(model, color, mpg)
self.battery_type = battery_type