如果我有一个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)
我哪里错了?
发布于 2013-10-06 14:06:47
您可以使用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'}
https://stackoverflow.com/questions/19205916
复制相似问题