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 trialMischa Potter
2,555 PointsIn 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.
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
14,242 PointsThere 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
Mischa Potter
2,555 PointsMischa Potter
2,555 PointsBoi hi!
boi
14,242 Pointsboi
14,242 PointsHey Mischa!!