Avoid Duplicate Animals
00:00
I don’t want to enter if the animal is already in the location. So that just means I want to check whether the animal is currently already in the location where I’m trying to move it to and let me update location
to new_location
to make this a bit more descriptive.
00:17
And so I don’t want to enter if it’s already in the location. So I’m going to check if self._location
is the same as the new_location
.
00:29
So I’m using the identity operator here just to make sure that it’s actually the same objects, as if self._location
points to the same object as new_location
, then I don’t want to move the animal because it’s already there.
00:44
So in that case, I’m just going to return and return with a descriptive f-string that reads, in curly braces, “self.name
” and then “is already here”. So in that case, I’m not going to enter.
01:01 So I am ending the method call with a return statement after the check because no need to move it there, it’s already there. Okay, so let’s assume this is clear. So it’s not here.
01:15
I will do another check if self._location
. So keep in mind that when I initialize one of these animal objects, then self._location
, I’m setting it to None
at the beginning.
01:31
So this check if self._location
checks basically if it’s not None
, but we can be more explicit here. So I’m going to say is not None
.
01:41
So if it has a location object associated to it, in that case I want to exit from that location because it’s not the same location that I’m trying to move it to, and it’s also not None
. In that case, I want to exit self._location.animals
, so I’m accessing the animals
list on that ._location
object.
02:07
And I will remove self
from that list.
02:12 Okay. Here I don’t want to return because this is just one of the steps. I first want to remove it from the old location and then I want to add it to the new location. So maybe I’m going to take a note here, maybe print a message. I’m not sure whether we’re going to need that or not, but it’s an option.
02:32
But otherwise, I think I’ve tackled these two tasks. That looks good. Before updating self._location
, I want to check whether it’s already there. If it is, end the method call right there. If it isn’t, but it is already in a different location object, then I want to remove it from that other location object before putting it into new_location
. Cool. Sounds good.
02:55
I think next we can update self._location
and then tackle the next tasks.
Become a Member to join the conversation.
Kyle E on May 17, 2024
At 2:06 Martin types “self._location.animals.remove(self)”
Where does “animals” come into play? From what I can tell, there is no “animals” to reference. Is it supposed to be “Animal”, referring to the class this method belongs to?
Perhaps this is the bug in the code referenced later but I do not understand this