Skip to content
Advertisement

class and defining __str__

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)

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement