我创建了一个Vehicle
类,并希望从它派生一个Car
类,调用父构造函数来设置name
和color
。但是我收到了这个错误:
super() takes at least 1 argument (0 given)
这是我的代码:
class Vehicle:
def __init__(self, name, color):
self.__name = name # __name is private to Vehicle class
self.__color = color
def getColor(self): # getColor() function is accessible to class Car
return self.__color
def setColor(self, color): # setColor is accessible outside the class
self.__color = color
def getName(self): # getName() is accessible outside the class
return self.__name
self.__model = model
def getDescription(self):
return self.getName() + self.__model + " in " + self.getColor() + " color"
class Car(Vehicle):
def __init__(self, name, color, model):
# call parent constructor to set name and color
super().__init__(name, color)
self.__model = model
def getDescription(self):
return self.getName() + self.__model + " in " + self.getColor() + " color"
# in method getDescrition we are able to call getName(), getColor() because they are
# accessible to child class through inheritance
c = Car("Ford Mustang", "red", "GT350")
print(c.getDescription())
答案 0 :(得分:3)
super()
不知道它正在调用哪个类。你必须告诉它你想要获得哪个类的父类方法。例如。代码中的super(Car, self).__init__(self, name, color)
。
答案 1 :(得分:2)
在Python 3中,这有效:
class Vehicle:
def __init__(self):
print('Vehicle __init__() called')
class Car(Vehicle):
def __init__(self):
super().__init__()
car = Car()
打印:
Vehicle __init__() called
在Python 2中尝试相同的操作会导致问题:
class Vehicle:
def __init__(self):
print('Vehicle __init__() called')
class Car(Vehicle):
def __init__(self):
super().__init__()
car = Car()
引发此异常:
Traceback (most recent call last):
...
TypeError: super() takes at least 1 argument (0 given)
我们需要首先提供自己的类,并将self
作为super()
的第二个参数提供:
class Vehicle:
def __init__(self):
print('Vehicle __init__() called')
class Car(Vehicle):
def __init__(self):
super(Car, self).__init__()
car = Car()
但这还不够:
Traceback (most recent call last):
...
TypeError: must be type, not classobj
class Vehicle:
创建一个旧式的类。 Vehicle
必须继承object
才能获得适用于super()
的新式课程:
class Vehicle(object):
def __init__(self):
print('Vehicle __init__() called')
class Car(Vehicle):
def __init__(self):
super(Car, self).__init__()
car = Car()
打印:
Vehicle __init__() called
在Python 2中没有参数的必须始终记住这两个论点有点烦人。幸运的是,有一个解决方案。强烈推荐的库Python-Future允许您在Python 2中使用不带参数的super()
:
from builtins import object, super # from Python-Future
class Vehicle(object):
def __init__(self):
print('Vehicle __init__() called')
class Car(Vehicle):
def __init__(self):
super().__init__()
car = Car()
打印:
Vehicle __init__() called