Create a .__str__()
00:00
Now that we have a parent location class and two child classes, let’s define a .__str__()
inside of the parent class so that all of the child classes get a nice output as well. def __str__(self):
And it takes self
.
00:18
And then we’re just going to return another f-string. So first of all, I want the .location_type
in there. And here is an advantage of having this defined as an instance attribute is that inside of the curly braces of the f-string, I can say self.location_type
.
00:37
And I’m not going to run into this issues with overriding .location_type
with a different instance attribute, because this is already an instance attribute.
00:46
So sure, I can still override it, but there’s not going to be any ambiguity then because there is no class attribute basically that I’m shadowing when I overwrite the .location_type
instance attribute. Remember what we did earlier for animals?
01:03
We took this little detour with going through the .__class__
attribute and then to the class attribute. And now I’m just skipping that because I defined .location_type
directly as an instance attribute. So it’ll make the code a little easier to read.
01:20
All right, and so I’m saying that the specific .location_type
has so and so many spaces filled. That would be an interesting information to have.
01:30
So I’ll put in curly braces here and put some code that calculates how many spaces are left. So I’ll say the length of the self.animals
list.
01:44
I’m not doing much of a calculation. I’m just going to say so and so many animals are already in that space. And I’m calculating that by getting the current length of the animals
list.
01:56
And then I’ll just represent it, putting a forward slash there. And then another curly braces where I’m going to print out self.spaces
. So it’ll say so and so many animals are currently in there out of so and
02:10 so many spaces that exist.
02:14 It was a little hard to describe what an f-string is going to do and usually always easier to just view it. So let me run this code and we’ll give it a try.
02:25
Now I should be able to create a Field
. I’m going to create an instance of Field
and say that there’s 10
animals that can fit on a field. And then if I print()
the Field
, it’ll tell me the Field
has 0
out of 10
spaces filled. Looks good.
02:40
Let’s make a Barn
. The Barn
is a little smaller than the Field
and only holds five animals. And then I can print()
the Barn
, and the string tells me the Barn
has 0
out of 5
spaces filled. Okay, that looks good.
02:55
That is a readable string representation of what’s going on in that Barn
or on that Field
. And also, it seems to be working so far.
03:04 Next, let’s put in an easier check to figure out whether or not one of those locations is already full.
Become a Member to join the conversation.