我创建了一个Vehicle类,并希望Car从它派生一个类,该类调用父构造函数来设置name和color。但是我收到此错误:
super() takes at least 1 argument (0 given)
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
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())
Run Code Online (Sandbox Code Playgroud)
在 Python 3 中,这有效:
class Vehicle:
def __init__(self):
print('Vehicle __init__() called')
class Car(Vehicle):
def __init__(self):
super().__init__()
car = Car()
Run Code Online (Sandbox Code Playgroud)
印刷:
Vehicle __init__() called
Run Code Online (Sandbox Code Playgroud)
在 Python 2 中尝试同样的事情会导致问题:
class Vehicle:
def __init__(self):
print('Vehicle __init__() called')
class Car(Vehicle):
def __init__(self):
super().__init__()
car = Car()
Run Code Online (Sandbox Code Playgroud)
抛出这个异常:
Traceback (most recent call last):
...
TypeError: super() takes at least 1 argument (0 given)
Run Code Online (Sandbox Code Playgroud)
我们需要提供自己的类作为第一个和self第二个参数 super():
class Vehicle:
def __init__(self):
print('Vehicle __init__() called')
class Car(Vehicle):
def __init__(self):
super(Car, self).__init__()
car = Car()
Run Code Online (Sandbox Code Playgroud)
但这还不够:
Traceback (most recent call last):
...
TypeError: must be type, not classobj
Run Code Online (Sandbox Code Playgroud)
class Vehicle:创建一个旧式类。Vehicle必须继承 fromobject才能获得一个适用于super()以下内容的新式类:
class Vehicle(object):
def __init__(self):
print('Vehicle __init__() called')
class Car(Vehicle):
def __init__(self):
super(Car, self).__init__()
car = Car()
Run Code Online (Sandbox Code Playgroud)
印刷:
Vehicle __init__() called
Run Code Online (Sandbox Code Playgroud)
必须一直记住这两个论点有点烦人。幸运的是,有一个解决方案。强烈推荐的库Python-Future允许您super()在 Python 2 中不带参数地使用:
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()
Run Code Online (Sandbox Code Playgroud)
印刷:
Vehicle __init__() called
Run Code Online (Sandbox Code Playgroud)
super()不知道它在哪个类中被调用。你必须告诉它你想要获取哪个类的父方法。例如super(Car, self).__init__(self, name, color)在您的代码中。