我创建了一个 Vehicle
类,还想从它派生一个 Car
类,调用父构造函数来设置 name
和 颜色
。但是我收到此错误:
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())
最佳答案
Python 3 - 不错
在 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 - 更多工作
在 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 中没有参数的 super()
不得不一直记住这两个参数有点烦人。幸运的是,有一个解决方案。强烈推荐的图书馆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
关于python - 我们可以向 super() 传递什么参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34496090/