0
class Person:
    pets=[]
    def add_pet(self, pet):
        self.pets.append(pet)

jane = Person()
bob = Person()

jane.add_pet("cat")
print(jane.pets)
print(bob.pets)

Print out:

['cat']
['cat']

why bob's pets is also cats? I didn't append pets to bob.

cdarke
  • 42,728
  • 8
  • 80
  • 84
Yi Lu
  • 9
  • 1

3 Answers3

0

Because you share the variable pets with every instance of Person.

class Person:
    def __init__(self):
        self.pets = []

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

This should do the trick.

pask
  • 899
  • 9
  • 19
0

The list pets is shared between all objects in the class because of where you declare it. You need a constructor, called __init__, which is called automagically when the object is created:

class Person:
    def __init__(self):
        self.pets = []

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


jane = Person()
bob = Person()

jane.add_pet("cat")
print(jane.pets)
print(bob.pets)

Gives:

['cat']
[]
cdarke
  • 42,728
  • 8
  • 80
  • 84
0

If you're expecting the pets to be an instance member:

class Person:
    def __init__(self):
        self.pets = []
    ...

Output:

['cat']
[]
Joseph D.
  • 11,804
  • 3
  • 34
  • 67