Python Object-Oriented Python Instant Objects Master Class

Mischa Potter
Mischa Potter
1,488 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

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

Hey Mischa!!