Home > Software engineering >  Calling a list from a class in Python
Calling a list from a class in Python

Time:11-16

If I call a list from a class, the output is not the content of the list.

I would like to call self.pets from the class Owner, but the output is not the content of the list, but that:

David Friend's pets are: [<__main__.Pet object at 0x7f547c620128>, <__main__.Pet object at 0x7f547c620198>]
Audrey Hepburn's pets are: [<__main__.Pet object at 0x7f547c620208>]
I expected my code to print this:

David Friend's pets are: Boggle Joyner, Artemis Joyner

Audrey Hepburn's pets are: Pippin Hepburn

Here is the code:

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 = []

def get_pets_string(an_owner):
    return str(an_owner.name.first)   " "   str(an_owner.name.last)   "'s pets are: "   str(an_owner.pets)


owner_1 = Owner(Name("David", "Friend"))
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(owner_2.name.first)
print(get_pets_string(owner_1))
print(get_pets_string(owner_2))

CodePudding user response:

This is because you are storing the pet objects in a list so it is printing out the object. You should overwrite the string function to fix this issue like so:

class Pet:
    def __init__(self, name, owner):
        self.name = name
        self.owner = owner

    def __str__(self):
        return self.name

The name class should be like so:

class Name:
    def __init__(self, first, last):
        self.first = first
        self.last = last

    def __str__(self):
        return self.first   " "   self.last

And the get pets function should be like so:

def get_pets_string(an_owner):
    res = str(an_owner.name.first)   " "   str(an_owner.name.last)   "'s pets are: "
    for pet in an_owner.pets:
        res  = str(pet)   ", "
    return res

This is if you would like to keep it like you have created it, however there are much easier ways of writing this code such as:

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

    def add_pet(self, pet: str):
        self.pets.append(pet)

    def get_pets(self):
        res = self.name   "'s pets are: "
        for pet in self.pets:
            res  = pet   ", "
        return res

o = Owner("David Friend")
o.add_pet("Boggle Joyner")
o.add_pet("Artemis Joyner")
print(o.get_pets())
  • Related