Pithikos
Pithikos

Reputation: 20300

How make new instances of a class in Python 3?

I came up on this weird behaviour in python. I want to make two difference instances of the class Numbers:

class Numbers:
   numberList=[]

   def __init__(self, *arg):
      for number in arg:
         self.numberList.append(number)


numbers=Numbers(4, 8)    # Instance 1
numbers=Numbers(7, 5, 3) # Instance 2
print(numbers.numberList)

Output:

[4, 8, 7, 5, 3]

Expected output:

[7, 5, 3]

I thought the part of my code where I do class instantiation would be equal to the usage of the keyword New found in other languages. However the outcome is totally different. Why is that? I want instance 1 to be totally replaced with instance 2, not concatenate the two.

Upvotes: 0

Views: 231

Answers (1)

falsetru
falsetru

Reputation: 369114

In the following code, numberList is class variable that is shared by all class instances.

>>> class Numbers:
...     numberList = []
... 
>>> n1 = Numbers()
>>> n2 = Numbers()
>>> Numbers.numberList is n1.numberList
True
>>> Numbers.numberList is n2.numberList
True

Change as follow to get per-instance instance variable (called data attribute in Python):

class Numbers:
    def __init__(self, *arg):
        self.numberList = []
        for number in arg:
            self.numberList.append(number)

Upvotes: 2

Related Questions