所以基本上我有一个父类,在 init() 中带有一些参数,现在我想定义一个子类,我想在 init() 中重新定义 init()子类只是在其中附加一个新参数。有什么方便的方法可以完成这个吗?
这是我的代码:
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
最佳答案
你可以使用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
关于python - 如何在子类的 __init__() 中附加另一个参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33116450/