I’m trying to do the excercise from the lesson on OOP.
We are supposed to:
- Define an animal class that has a friends attribute , which is a list of all of that animal’s friends.
- Define a method that takes as an argument another object of the same class and appends its name to the current’s animal friend list and vice versa.
I did the exercise using a Turtle type, and got an unusual behavior that I could not understand.
In short, I defined a make_friends method that can be applied on a Turtle object. This method takes a seond Turtle object as an argument and appends each turtle’s name to the other one’s friend list.
HOWEVER, for some reason, this results in both turtles being added to each ones list instead of to just the other turtle’s list, so that I end up with two identical lists for each turtle.
This is the code I wrote:
def become_friend(self,friend): if type(friend)!=Turtle: print("Friend must also be of type \"Turtle\"") else: if friend.is_sea!=self.is_sea: print("Friend must be same type of turtle, sea and land turtles don't get along!!") else: self.friends.append(friend.name) friend.friends.append(self.name)
I expected to get:
But instead got: