我通过制作汽车程序从事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)
有什么想法吗?
答案 0 :(得分:0)
在python 2.7中,当我改变你的
时super().__init__(make, model, year)
到
Car.__init__(self, make, model, year)
一切似乎都有效。输出是:
2016特斯拉Model S