Welcome to the Treehouse Community
Looking to learn something new?
Anthony Grodowski4,902 Points
I've got a problem!
I stilll don't get that whole self thing... Also how can i use kwargs in my code? I get that kwargs is useful in creating a new instance in the REPL but how could it be in the main code? I'm really confused and be so grateful for any help!
class RaceCar: laps = 0 def __init__(self, color, fuel_remaining, laps = RaceCar.laps, **kwargs): self.fuel_remaining = fuel_remaining self.color = color for key, value in kwargs.items(): setattr(self, key, value) def run_lap(self, length): self.fuel_remaining -= length * 0.125 RaceCar.laps += 1
Chris FreemanTreehouse Moderator 68,179 Points
Good question! When defining a class method you are required to provide a parameter that will be used to hold a reference to the class instance. This
self parameter gets assigned to a value (the instance id. It’s location in memory) when the class instance is created. That is why you don’t need to provide the
self parameter when calling class methods. Since
self points to the instance, all the attributes can be referenced used the “dot” notation of
Each object has a Namespace dict that holds its attributes, name of methods, etc. The class
RaceCar has its own. Each instance of the class also has its own NameSpace of attributes, etc. When looking up a reference, the local instance NameSpace is checked first, if not found then the class NameSpace is checked.
When setting any attribute using
self.attribute = value, the attribute immediately becomes entered into the instance NameSpace thus becoming a local variable to the class instance. The class attribute
laps becomes overridden (or in a sense hidden) from the instance because the local
laps is found first.
The **kwargs is used to receive an unknown number of keyword arguments. The variable
kwargs is referenced to unpack the key/value pairs when needed.
RaceCar.laps refers to the class attribute
laps. It can’t be referenced inside of
RaceCar because it hasn’t finished being defined yet. It doesn’t yet exist.
There are some errors in your code:
lapsneeds to set to a default value of 0, as in
- the instance attribute
self.lapsmust be assigned to the argument passed into
laps. This is done the same way as
RaceCar.run_lap(), it is the instance attribute
self.lapsthat needs to be set.
RaceCar.lapsis not yet defined
Edits: fixed typo
self,attribute should be
self.attribute Expanded answer.
Post back if you need more help. Good luck!!!