Question
How does init know what values to assign to instance variables?
Answer
If we make an __init__()
method that accepts the same parameters as our Car
class, like this: (self, model, color, mpg)
, then these are the values that will be provided whenever you create a new Car
object.
When a new Car
object is created, the values provided as arguments for those parameters are then given to you for use inside the __init__()
method. That’s where we’re able to create new instance variables with the structure: self.variable_name = variable_name
. The left side uses self
to tell Python to create a new instance variable for this particular object we just made, and then the right side is the value we store in that new variable, which is just the argument value.