Shared lists in instances of classes (objects) [duplicated]

0

I have the following code

class Num(object):

    i = list()
    def __init__(self):
        pass

    def imp(self):
        print(self.__i)

    def add(self, n):
        self.__i.append(n)
from Num import *

n1 = Num()
n2 = Num()

n1.add(10)
n1.imp()

n2.add(1)
n2.imp()

and I get the following result

  • In n1 printing I get 10
  • In n2 printing I get 10.1

My question is, why if there are 2 different objects does append to the same list?

It is assumed that if I just modify the list of the object n1 or n2 it should have the values defined for each object.

    
asked by Bashunter 20.06.2018 в 08:07
source

1 answer

0

The problem is because you created a variable which is shared among all instances of the class. To avoid that, try defining them within __init__ :

class Num(object):
    def __init__(self):
        self.__i = list()

    def imp(self):
        print(self.__i)

    def add(self, n):
        self.__i.append(n)

In this way the variables will become local to each instance of the class Num .

    
answered by 22.06.2018 в 03:55