The first class contains the car details and in the second Service
class using the get_car_by_year()
method. I need to return car based on the date of manufacturing using get_*
function of the first class, but I am getting None
no matter which year I enter.
Code:
class Car:
def __init__(self,model,year,registration_number):
self.__model=model
self.__year=year
self.__registration_number=registration_number
def get_model(self):
return self.__model
def get_year(self):
return self.__year
def get_registration_number(self):
return self.__registration_number
def __str__(self):
return(self.__model " " self.__registration_number " " (str)(self.__year))
class Service:
def __init__(self,car_list):
self.__car_list = car_list
def get_car_by_year(self,year):
result_list = []
for car in self.__car_list:
if(car.get_year() == year):
result_list.append(car.get_model())
if(len(result_list) == 0):
return None
return result_list
car1=Car("WagonR",2010,"KA09 3056")
car2=Car("Beat", 2011, "MH10 6776")
car3=Car("Ritz", 2013,"KA12 9098")
car4=Car("Polo",2013,"GJ01 7854")
car5=Car("Amaze",2014,"KL07 4332")
car_list=[car1, car2, car3, car4,car5]
a1 = Service(car_list)
print(a1.get_car_by_year(2013))
CodePudding user response:
Your return statements are inside loop which will always return null, because the first car in your car list is WagonR which is 2010. If you would call your current function get_car_by_year with a 2010 year you will get your desired output. Placing both return statements outside for loop will do the trick
def get_car_by_year(self,year):
result_list = []
for car in self.__car_list:
if(car.get_year() == year):
result_list.append(car.get_model())
if (len(result_list) == 0):
return None
return result_list
CodePudding user response:
def get_car_by_year(self,year):
result_list = []
for car in self.__car_list:
if(car.get_year() == year):
result_list.append(car.get_model())
return None if len(result_list) == 0 else result_list