Home > Back-end >  trying to append to another class list with the initialization of another class instance
trying to append to another class list with the initialization of another class instance

Time:06-26

I working through a problem- adjusting the Pet, Owner, and Name classes in order to get the Owner Pets list to fill with the initialization of the Pet instance. I am running into issues filling a list across classes and have tried several ways - from stepping into the Owner class from the Pet Class, appending to a list in Pet, and setting a list in Owner == to the Pet class (but I can see why this wouldn’t work). I either get attribute or name errors and can’t seem to get insight by using my googlefu, any help would be great! Here’s where I am currently. I’m getting no errors, but now I’ve got an empty Owner’s list and a nicely populated set of Pet lists…

class Name:

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

class Owner:

    def __init__(self, name):
        self.name = name
        self.pets = [] #this is the list I'm trying to append to when an instance of Pet initializes.

class Pet:

    def __init__(self, name, owner):
        self.name = name
        self.owner = owner
        self.pets = []
        Owner(self.pets.append(self.name.first))

CodePudding user response:

You have to use self.owner instead of Owner(). And if you want to keep instance then you should append self


Minimal working code:

class Name:

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

class Owner:

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

class Pet:

    def __init__(self, name, owner):
        self.name = name
        self.owner = owner
        self.owner.pets.append(self)
        
# --- main ---

person = Name('James', 'Bond')
owner = Owner(person)
pet1 = Pet("Lassie", owner)
pet2 = Pet("Kermit", owner)
pet3 = Pet("Jumbo", owner)

print('Owner:', owner.name.first, owner.name.last)
for pet in owner.pets:
    print('Pet  :', pet.name)
print('---')

print('Pet  :', pet1.name)
print('Owner:', pet1.owner.name.first, pet1.owner.name.last)
print('---')

print('Pet  :', pet2.name)
print('Owner:', pet2.owner.name.first, pet2.owner.name.last)
print('other Pets for the same Owner:')
for pet in pet2.owner.pets:
    if pet != pet2:
        print('  >', pet.name)
print('---')

Result:

Owner: James Bond
Pet  : Lassie
Pet  : Kermit
Pet  : Jumbo
---
Pet  : Lassie
Owner: James Bond
---
Pet  : Kermit
Owner: James Bond
other Pets for the same Owner:
  > Lassie
  > Jumbo
---
  • Related