Attribute friends
belong to a person and is different for each person.
This means friends
should be an instance variable rather than class variable.
class Person:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.friends = [] # person can have a list of friends
def add_friend(self, friend):
" Add a friend for this person "
self.friends.append(friend)
def get_name(self):
return self.first_name + " " + self.last_name
def get_friends(self):
" List of friends as a string "
return self.friends # returns list of friends
def __str__(self):
""" Converts attributes of person to string
(useful for print) """
return self.get_name()
Example Usage
# Example
p = Person('Bob', "Johnson")
# Add some friends (uses Person constructor to create persons)
p.add_friend(Person("Mary", "Sullivan"))
p.add_friend(Person("Jodie", "Oliver"))
p.add_friend(Person("Danny", "Washington"))
# Show p's friends
print(f'Person: {p}') # uses __str__ Person method to convert p to string
# for printing
print('Friends')
for friend in p.get_friends():
print('\t', friend) # since friend is a Person, Person method __str__
# knows how to convert to string for printing
Output
Person: Bob Johnson
Friends
Mary Sullivan
Jodie Oliver
Danny Washington