在Python汽车计划中的继承
问题描述:
我正在通过制作汽车程序来处理Python中的继承,但遇到了构建问题。下面是我的代码:在Python汽车计划中的继承
class Car():
"""A simple attempt to represent a car"""
def __init__(self, make, model, year):
"""Initialize attributes to describe a car."""
self.make = make
self.model = model
self.year = year
#setting a default value for an attribute#
self.odometer_reading = 0
def get_descriptive_name(self):
"""Return a neatly formatted descriptive name."""
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
"""Print a statement showing the car's mileage."""
print("This car has " +str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
"""Modifying the value through the following method
Reject the change if it attempts to roll the odometer back
"""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
"""Incremeting an attributes value through methods"""
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())
但是,我越来越想运行的程序时,此错误消息:
Traceback (most recent call last):
File "electric_car.py", line 39, in <module>
my_tesla = ElectricCar('tesla', 'model s', 2016)
File "electric_car.py", line 37, in __init__
super().__init__(make, model, year)
TypeError: super() takes at least 1 argument (0 given)
任何想法?
答
在Python 2.7版,当我改变你的
super().__init__(make, model, year)
到
Car.__init__(self, make, model, year)
一切似乎工作。输出是:
2016 Tesla Model S
错误似乎很清楚:*“TypeError:super()至少需要1个参数(给出0)”*您可能正在使用Python 2.x. –
啊,就是这样,似乎我需要升级到Python 3.谢谢! –
另外,你可能想从'object'扩展'Car' –