0

having the nex class:

class Person(object):
    name = ""
    arrayTest = []
    def __init__(self, name, item):
        self.name = name
        self.arrayTest.append(item)

    def speak(self):
        print "Hi! My name is ", self.name
        print "And my sons are: "
        print self.arrayTest


basil = Person("Basil", "Sofia")
basil = Person("Basil", "Julia")
basil.speak()

>>> Hi! My name is  Basil
And my sons are:
['Sofia', 'Julia']

polly = Person("Polly", "Peter")
polly.speak()

>>>Hi! My name is  Polly
And my sons are:
['Sofia', 'Julia', 'Peter']

I would expect the second instance returns only Peter as son of Polly but it was not,

What I'm doing wrong?

Thank you!!

Luis
  • 1,040
  • 1
  • 14
  • 22
  • 4
    When you put `arrayTest = []` directly in the class and outside `__init__` like that you're telling Python you want to share this list between every instance of the class. That is how you create **shared class variables**, which is not what you want. It's a very common mistake but I don't have a good duplicate target in-hand. – Two-Bit Alchemist Sep 03 '15 at 16:05
  • By the way, also the output of `basil.speak()` should surprise you. – Andrea Corbellini Sep 03 '15 at 16:07
  • Ok, thank you very much!! Andrea Corbellini – Luis Sep 03 '15 at 16:20
  • Ok, thank you very much!! Two-Bit Alchemist – Luis Sep 03 '15 at 16:27

0 Answers0