0

How could I modify the classes below so that when a new instance of Pet is created, it is automatically added to its Owner's list of pets?

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 = []
1
  • in Pet.__init__(): self.owner.pets.append(self) Commented May 27, 2021 at 21:45

1 Answer 1

2
owner1 = Owner(name="Juan")

pet = Pet(name="foo", owner=owner1)

owner1.pets += pet

or change your pet init

class Pet:
    def __init__(self, name, owner):
        self.name = name
        self.owner = owner
        owner.pets.append(self)
Sign up to request clarification or add additional context in comments.

5 Comments

Realy no, fixed!
You can't concatenate a non-iterable to a list. Change it to owner.pets += [self]
Or how about owner.pets.append(self)?
yeah, sorry, that "owner.pets.append(self)" is the correct syntax, seeing that self will be an object, and objects is not iterable
Excellent, many thanks. The change on pet init worked perfectly!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.