I'm new to Python and am trying to code Python classes. But in the following, I get "unexpected argument" error, for the attributes of car_1, car_2 and car_3 (in bold). How to correct it? Or is it a Pycharm issue? Thanks!
import random
class Vehicle:
def _init_(self, make, model, year, weight):
self.make = make
self.model = model
self.year = year
self.weight = weight
class Car(Vehicle):
def _init_(self, make, model, year, weight, is_driving=True, trips_since_maintenance=0, needs_maintenance=False):
super().__init__(make, model, year, weight)
self.is_driving = is_driving
self.trips_since_maintenance = 0
self.needs_maintenance = needs_maintenance
def drive(self):
drive = 0
if drive > 0:
self.is_driving = True
def stop(self):
stop = 0
while self.drive():
stop += 1
break
self.is_driving = False
self.trips_since_maintenance += 1
if self.trips_since_maintenance >= 100:
self.needs_maintenance = True
def repair(self):
self.needs_maintenance = False
self.trips_since_maintenance = 0
def randomly_drive_car(car):
drive_times = random.randint(1, 101)
for i in range(drive_times):
Car.drive()
Car.stop()
**car_1 = Car('Honda', 'City', '2018', '1153 kg')
car_2 = Car('Toyota', 'Altis', '2018', '1745 kg')
car_3 = Car('Mazda', '_3', '2020', '1260 kg')**
randomly_drive_car(car_1)
randomly_drive_car(car_2)
randomly_drive_car(car_3)
It's all correct except that you need to put two underscores for init methods.
class Vehicle:
def __init__(self, make, model, year, weight):
...
class Car(Vehicle):
def __init__(self, make, model, year, weight, is_driving=True, trips_since_maintenance=0, needs_maintenance=False):
super().__init__(make, model, year, weight)
EDIT:
At line 42/43 you're calling 'Car.drive', you should be calling 'car.drive()' (lowercase C) because your function parameter is called 'car'. By using Car.drive()
you're trying to call the drive method as a class method.
EDIT 2 (from comments):
import random
class Car(Vehicle):
...
def take_trip(self):
self.trips_since_maintenance += 1
if self.trips_since_maintenance >= 100:
self.needs_maintenance = True
def randomly_drive_car(car):
drive_times = random.randint(1, 101)
for i in range(drive_times):
car.take_trip()
car_1 = Car('Honda', 'City', '2018', '1153 kg')
car_2 = Car('Toyota', 'Altis', '2018', '1745 kg')
car_3 = Car('Mazda', '_3', '2020', '1260 kg')
randomly_drive_car(car_1)
randomly_drive_car(car_2)
randomly_drive_car(car_3)