Create a .__str__()
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
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
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?
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.
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
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
Field, it’ll tell me the
0 out of
10 spaces filled. Looks good.
Let’s make a
Barn is a little smaller than the
Field and only holds five animals. And then I can
Barn, and the string tells me the
0 out of
5 spaces filled. Okay, that looks good.
Become a Member to join the conversation.