Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Object-Oriented Python Instant Objects Master Class

Mischa Potter
Mischa Potter
2,555 Points

In Python, attributes defined on the class, but not an instance, are universal. So if you change the value of the RaceCa

What is wrong with this code? You are supposed to change the laps attribute to 0 and i have tried doing it many times but it doesnt work.

racecar.py
class RaceCar:
laps = 0
    def __init__(self, color, fuel_remaining, laps = 0, **kwargs):
        self.color = color
        self.fuel_remaining = fuel_remaining

        for keys, values in kwargs.items():
            setattr(self, keys, values)

    def run_lap(self, length):
        self.fuel_remaining -= (length * 0.125)
        self.laps += 1

1 Answer

boi
boi
14,242 Points

There are two ways you can play this

class RaceCar:
#laps = 0 👈#Remove this line of code, it's an error, you don't put an attribute like that.
    def __init__(self, color, fuel_remaining, laps = 0, **kwargs):
        self.color = color
        self.fuel_remaining = fuel_remaining

        for keys, values in kwargs.items():
            setattr(self, keys, values)

    def run_lap(self, length):
        self.fuel_remaining -= (length * 0.125)
        self.laps += 1

Now, let's focus on the run_lap method. If you want to use self.laps += 1 you have to set an attribute in the __init__ method same like self.color and self.fuel_remaining, in this case, it will be self.laps = laps

class RaceCar:
    def __init__(self, color, fuel_remaining, laps = 0, **kwargs):
        self.color = color
        self.fuel_remaining = fuel_remaining
        self.laps = laps 👈#Attribute is set here

        for keys, values in kwargs.items():
            setattr(self, keys, values)

    def run_lap(self, length):
        self.fuel_remaining -= (length * 0.125)
        self.laps += 1👈#This is now valid
class RaceCar:
    def __init__(self, color, fuel_remaining, laps = 0, **kwargs):
        self.color = color
        self.fuel_remaining = fuel_remaining

        for keys, values in kwargs.items():
            setattr(self, keys, values)

    def run_lap(self, length):
        self.fuel_remaining -= (length * 0.125)
        laps += 1👈#Removed "self" because no attribute is set in the __init__ method, now this is valid