Adding an Instance Method
The task was to add an instance method called
.drive() that takes some
miles as an argument. Then that should increment
self.mileage for how many
miles you passed in and then test it. So I want to define
.drive(), and this instance method won’t be a special method like the first two with the double underscores.
But this is just a method that is public to the
Car class and that I’m going to define now. And still, it takes
self as its first argument because I want to do something on the instance of the
Car, and then it also takes another argument.
So I put in the parameter
miles in the method definition, and that just means that when calling
Car.drive(), you have to pass in
miles. That’s going to be a number. And then what do you want to do with this?
0 miles. Actually, just for fun, this
car is going to be
0 miles. Okay, so we have this
Car object. If I
The white car has 0 miles. And now I should be able to say
I’m going to drive this car for a hundred miles, no output. But something happened in here because now if I
print(car), it tells me that
The white car has 100 miles. So with this instance method here, with
.drive(), I accessed an instance attribute,
.mileage, and changed it basically with whatever I input here as an argument. So that works.
Become a Member to join the conversation.