Pra*_*ava 89 python inheritance constructor python-2.7
如果我有一个python类:
class BaseClass(object):
#code and the init function of the base class
Run Code Online (Sandbox Code Playgroud)
然后我定义了一个子类,例如:
class ChildClass(BaseClass):
#here I want to call the init function of the base class
Run Code Online (Sandbox Code Playgroud)
如果基类的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)
Run Code Online (Sandbox Code Playgroud)
我哪里错了?
Min*_*gyu 107
你可以用 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)
Run Code Online (Sandbox Code Playgroud)
你的缩进是不正确的,这是修改后的代码:
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__
Run Code Online (Sandbox Code Playgroud)
这是输出:
{'color': 'golden', 'mpg': 10, 'model': 'ford', 'battery_type': 'battery'}
Run Code Online (Sandbox Code Playgroud)
Man*_*ddy 35
正如Mingyu指出的那样,格式化存在问题.除此之外,我强烈建议在调用时不要使用Derived类的名称,super()
因为它会使代码不灵活(代码维护和继承问题).在Python 3中,请super().__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().__init__(model, color, mpg)
Run Code Online (Sandbox Code Playgroud)
感谢Erwin Mayer在使用__class__
super()时指出了问题
the*_*eye 11
你可以像这样调用超类的构造函数
class A(object):
def __init__(self, number):
print "parent", number
class B(A):
def __init__(self):
super(B, self).__init__(5)
b = B()
Run Code Online (Sandbox Code Playgroud)
注意:
这仅在父类继承时才有效 object
如果你使用的是Python 3,建议简单地调用super()而不使用任何参数:
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().__init__(model, color, mpg)
car = ElectricCar('battery', 'ford', 'golden', 10)
print car.__dict__
Run Code Online (Sandbox Code Playgroud)
不要使用类调用super,因为根据此答案可能会导致无限递归异常.
归档时间: |
|
查看次数: |
121840 次 |
最近记录: |