在下面的代码中,我不断得到相同的错误,尽管我重新检查了超过15分钟。关于你的信息,我在sublime文本上运行了它,错误如下:
TypeError: super() takes at least 1 argument (0 given)
代码如下所示:
class Car():
"""A simple attempt to represent a car."""
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
self.odometer_reading += miles
class ElectricCar(Car):
"""Represent aspects of a car, specific to electric vehicles."""
def __init__(self, make, model, year):
"""Initialize attributes of the parent class."""
super().__init__(make, model, year)
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
这里的问题是StackOverflow上的一个相当大的问题。但我会解释你是如何错误地使用} ,可以在Python 2.2及以上版本中使用(Python 3专门使用新样式类)
super()
。您正在使用所谓的Old Style classes,同时尝试使用super()
新样式类继承自^{您的
Car
类声明应该如下所示->class Car(object):
(Car
继承自object
内置的),您的super
调用具有对象所在的类,并且self
作为参数传入:现在,如果我们打印出对象的类型是:
我们可以看到它的类型是
ElectricCar
为什么这一切都很重要?这些风格之间有一些关键的区别。在旧样式中,类及其为实例化定义的对象属于不同的类型。在旧式类中,实例总是
instance
类型,而不管它们的类是什么。对于新样式的类,实例通常将与其类共享相同的类型。示例:旧式
新风格->
请参阅Python关于^{} 的官方文档
相关问题 更多 >
编程相关推荐