Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to return a list called in a class in python

Struggling with this:

Write a function called get_pets_string. get_pets_string should
have one parameter, an instance of Owner. get_pets_string
should return a list of that owner’s pets according to the
following format:

David Joyner's pets are: Boggle Joyner, Artemis Joyner
class Name:
    def __init__(self, first, last):
        self.first = first
        self.last = last

class Pet:
    def __init__(self, name, owner):
        self.name = name
        self.owner = owner
        
class Owner:
    def __init__(self, name):
        self.name = name
        self.pets = []

If your function works correctly, this will originally
print:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

David Joyner's pets are: Boggle Joyner, Artemis Joyner
Audrey Hepburn's pets are: Pippin Hepburn
owner_1 = Owner(Name("David", "Joyner"))
owner_2 = Owner(Name("Audrey", "Hepburn"))

pet_1 = Pet(Name("Boggle", "Joyner"), owner_1)
pet_2 = Pet(Name("Artemis", "Joyner"), owner_1)
pet_3 = Pet(Name("Pippin", "Hepburn"), owner_2)

owner_1.pets.append(pet_1)
owner_1.pets.append(pet_2)
owner_2.pets.append(pet_3)

print(get_pets_string(owner_1))
print(get_pets_string(owner_2))

Here is my code as below:

def get_pets_string(owner):
    for obj in owner.pets:
       return owner.name.first + " " + owner.name.last + "'s pets are: " + obj.name.first + " " + obj.name.last

My answer can only print one pet for each owner like this:

David Joyner's pets are: Boggle Joyner
Audrey Hepburn's pets are: Pippin Hepburn

>Solution :

You can implement a quick helper function to change how the string is displayed and simply displaying the name:

def repr_name(name):
    return name.first + " " + name.last

Then you can display all the pets together:

def get_pets_string(owner):
   return f"{repr_name(owner.name)}'s pets are: {', '.join([repr_name(pet.name) for pet in owner.pets])}"

The ', '.join([str(pet.name) for pet in owner.pets]) puts the name of every pet into the list, and then separates each of them with commas.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading