我们可以将什么参数传递给super()?

时间:2015-12-28 15:18:13

标签: python python-2.7

我创建了一个Vehicle类,并希望从它派生一个Car类,调用父构造函数来设置namecolor。但是我收到了这个错误:

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())

2 个答案:

答案 0 :(得分:3)

super()不知道它正在调用哪个类。你必须告诉它你想要获得哪个类的父类方法。例如。代码中的super(Car, self).__init__(self, name, color)

答案 1 :(得分:2)

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允许您在Py​​thon 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