Home > Software design >  Trying to access items stored in a list in a class in Python but keep getting the object location
Trying to access items stored in a list in a class in Python but keep getting the object location

Time:06-13

I have several classes that were built, one that includes a list of items, and I have to access the list from a function call, using one of the other classes. The issue is, that when I try to access it, I keep getting the object, rather than the list of items in the class.

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


def get_pets_string(a_owner):
    result = "{0} {1}'s pets are: {2}.".format(a_owner.name.first, a_owner.name.last, a_owner.pets)
    return result

I get the owner names just fine, and I know the pet names are in the list, but cannot access them at all. I've tried using a_owner.pets.name in various ways, I've tried to access the main class, but I am not sure what I'm missing.

CodePudding user response:

Something like this?

class Name():
    def __init__(self, first: str, last: str) -> None:
        self.first = first
        self.last = last

class Owner:
    def __init__(self, name: Name, pets: list) -> None:
        self.name = name
        self.pets = pets

    def get_pets_names(self) -> list:
        pets_names = []
        for pet in self.pets:
            pets_names.append(pet.first)
        return pets_names

def get_pets_string(a_owner: Owner) -> str:
    result = "{0} {1}'s pets are: {2}.".format(a_owner.name.first, a_owner.name.last, a_owner.get_pets_names())
    return result

a_owner = Owner(Name("John", "Smith"), [Name("Cat", None), Name("Dog", None)])
print(get_pets_string(a_owner))

CodePudding user response:

a_owner.pets will give you the list. You can pretty-print it in this way:

from pprint import pp

pp(a_owner.pets)

If there's anything in the list, so len(a_owner.pets) > 0, then a_owner.pets[0] will give you the 1st element.

To conveniently format all list elements into a single string you can use this .join() expression:

print(', '.join(a_owner.pets))
  • Related