如何从子类调用基类的__init__方法? [英] How to call Base Class's __init__ method from the child class?
本文介绍了如何从子类调用基类的__init__方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个python类:
class BaseClass(object):
#code和init基类的函数
然后我定义一个子类,如:
class ChildClass(BaseClass):
#here我想调用基类的初始化函数
如果基类的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)
$ b b
我会出错吗?
解决方案
您可以使用 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汽车):
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':' mpg':10,'model':'ford','battery_type':'battery'}
If I have a python class as:
class BaseClass(object):
#code and the init function of the base class
And then I define a child class such as:
class ChildClass(BaseClass):
#here I want to call the init function of the base class
If the init function of the base class takes some arguments that I am taking them as arguments of the child class's init function, how do I pass these arguments to the base class?
The code that I have written is:
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)
Where am I going wrong?
解决方案
You could use 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)
Your indentation is incorrect, here's the modified code:
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__
Here's the output:
{'color': 'golden', 'mpg': 10, 'model': 'ford', 'battery_type': 'battery'}
这篇关于如何从子类调用基类的__init__方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文