Writing the .__init__()
00:00
Here I am in a new file and, like usual, I’m going to start again with just taking notes of the tasks that I have to do in code comments. So first, it was to create a Car
class.
00:11
That Car
class should have two instance attributes,
00:16
.color
, and I think that should be a string. And then also .mileage
, which should be an integer. And finally, create two instances and print .color
and .mileage
.
00:34
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 Car
class, class Car: pass
, and we’re done with the first task.
00:55
Now I need two instance attributes, .color
and .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 Car
.
01:14
In this case, it’s going to be .color
and .mileage
.
01:19
And then you need to assign them to the instance. self.color
equals the color that you pass when creating the Car
instance and self.mileage
equals mileage
.
01:32
So that means I have two instance attributes, .color
and .mileage
. I’m not specifying here that these are strings and integers.
01:40 There are ways to do this in Python using type hints, but for now, you’re just getting started with writing classes. So we’re not going to overcomplicate this and just keep it like this.
01:50
And then we need to create two instances and print .color
and .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 blue_car
.
02:19
There you go. And I should be able to just print out .color
and .mileage
. f"{blue_car.color}"
—well, that’s not a great thing.
02:29
f"The {blue_car.color} car has {blue_car.mileage} miles."
02:41
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.