Writing the .__init__()
And I’m probably going to do this using a
.__str__() method so that it prints out nicely when I call
print() and pass it a
Car instance. Let’s get started. Create a
class Car: pass, and we’re done with the first task.
Now I need two instance attributes,
.mileage. So again, instance attributes are going to go in the
.__init__() method that takes as its first argument
self and then whatever arguments I want to require for creating a
And then we need to create two instances and print
.mileage. I could already be printing that. Let’s try it out. So I run this, F5, and it gives me access to the
Car class so I can make a blue car using
Car() and then add in
"blue" for the color, and mileage was
20_000, I think. And so now I have a
The blue car has 20000 miles. All right, so this works. This is really the full task, but we’re going to make this a bit nicer and reuse this f-string or change it a little bit and put it in the
.__str__() so that then I can just print
blue_car and then get a nicer looking output than just this default reference to the
Car object and its memory location.
Become a Member to join the conversation.