如果我有一个python类:
class BaseClass(object):
#code and the init function of the base class
然后定义一个子类,例如:
class ChildClass(BaseClass):
#here I want to call the init function of the base class
如果基类的init函数接受某些参数,而我将它们作为子类的init函数的参数,则如何将这些参数传递给基类?
我写的代码是:
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
class ElectricCar(Car):
def __init__(self, battery_type, model, color, mpg):
self.battery_type=battery_type
super(ElectricCar, self).__init__(model, color, mpg)
我要去哪里错了?
你可以用 super(ChildClass, self).__init__()
class BaseClass(object):
def __init__(self, *args, **kwargs):
pass
class ChildClass(BaseClass):
def __init__(self, *args, **kwargs):
super(ChildClass, self).__init__(*args, **kwargs)
您的缩进不正确,这是修改后的代码:
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
class ElectricCar(Car):
def __init__(self, battery_type, model, color, mpg):
self.battery_type=battery_type
super(ElectricCar, self).__init__(model, color, mpg)
car = ElectricCar('battery', 'ford', 'golden', 10)
print car.__dict__
这是输出:
{'color': 'golden', 'mpg': 10, 'model': 'ford', 'battery_type': 'battery'}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句