class and defining __str__

Question:

This is the exercise:

Write the special method __str__() for CarRecord.

Sample output with input: 2009 'ABC321'

Year: 2009, VIN: ABC321

The following code is what I have came up with, but I’m receiving an error:

TYPEERROR: __str__ returned non-string

I can’t figure out where I went wrong.

class CarRecord:
    def __init__(self):
        self.year_made = 0
        self.car_vin = ''


    def __str__(self):
        return "Year:", (my_car.year_made), "VIN:", (my_car.car_vin)

   

my_car = CarRecord()
my_car.year_made = int(input())
my_car.car_vin = input()

print(my_car)
Asked By: user15344330

||

Answers:

You’re returning a tuple using all those commas. You should also be using self, rather than my_car, while inside the class. Try like this:

    def __str__(self):
        return f"Year: {self.year_made}, VIN: {self.car_vin}"

The f before the string tells Python to replace any code in braces inside the string with the result of that code.

Answered By: Albert
class Car:
    def __init__(self):
        self.model_year = 0
        self.purchase_price = 0
        self.current_value = 0
        def print_info():
            print('Car Info') # It specifies a print_info class method but doesnt actually need to print anything useful.

    def calc_current_value(self, current_year):
        depreciation_rate = 0.15
        car_age = current_year - self.model_year
        self.current_value = round(self.purchase_price * (1 - depreciation_rate) ** car_age)
    
    
    def print_info(self):
       print("Car's information:")
       print("   Model year:", self.model_year)
       print("   Purchase price:", self.purchase_price)
       print("   Current value:", self.current_value)

if __name__ == "__main__":    
    year = int(input()) 
    price = int(input())
    current_year = int(input())
    
    my_car = Car()
    my_car.model_year = year
    my_car.purchase_price = price
    my_car.calc_current_value(current_year)
    my_car.print_info()
Answered By: Lana Del Slay
def __str__(self):
       return "Year: {}, VIN: {}".format(self.year_made, self.car_vin)

The trick here is that you pull values from the top of the class as they are set later in the code.

Answered By: 742_742

This answer works for grading

def __str__(self):
    return f"Year: {}, VIN: {}".format(self.year_made, self.car_vin)`

This is easier to understand

def __str__(self):
    f"Year: {self.year_made}, VIN: {self.car_vin}")
Answered By: rickywmills
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.