1

I want to create array of objects in python.

class user:
    j = [0, 0]

AllUsers = []
AllUsers.append(user)
AllUsers.append(user)

AllUsers[0].j[0] = 1

for i in AllUsers:
    print(i.j)

And I expect output:

[1, 0]
[0, 0]

but am getting:

[1, 0]
[1, 0]

Where is the mistake?

So, I have seen a similar problems with "array of arrays", but I can't use their solution.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • I don't see any arrays. And your indentation is off. – Andras Deak -- Слава Україні Jul 15 '17 at 11:05
  • The answer to your question lies in class vs instance attributes. Consider reading [a python tutorial](https://docs.python.org/3/tutorial/index.html). – Andras Deak -- Слава Україні Jul 15 '17 at 11:07
  • 1
    You aren't putting different instances of class `user` in the `AllUsers` list, you're putting multiple references to the class itself in it. However even if you put different instances in (by creating them with `user()`), you would still have the problem because `j` has been defined as a class-level attribute, meaning it's shared by all instances of the class. The result—either way—is that changing the value of `j` through any of them effectively changes it in all the existing members of the list. – martineau Jul 15 '17 at 11:28
  • 2
    Possible duplicate of [Python: Difference between class and instance attributes](https://stackoverflow.com/questions/207000/python-difference-between-class-and-instance-attributes) – Andras Deak -- Слава Україні Jul 15 '17 at 12:12

2 Answers2

3

You are confusing instances and classes. Here is a working example:

class user:
    def __init__(self):
        self.j = [0, 0]


AllUsers = []
AllUsers.append(user())  # note the extra () which creates a new instance
AllUsers.append(user())

AllUsers[0].j[0] = 1

for i in AllUsers:
    print(i.j)
Alex Hall
  • 34,833
  • 5
  • 57
  • 89
0

I think this is the code you tried to paste in?

class user:
    j = [0, 0]

AllUsers = []
AllUsers.append(user)
AllUsers.append(user)

AllUsers[0].j[0] = 1

for i in AllUsers:
    print(i.j)

There are two main problems. First, AllUsers is a list, not an array. Second, you're appending a class to the list, not an instance of that class. To achieve what you're aiming for, you need to create an instance of the user class that you append. That would look something more like

AllUsers.append(user())

For the sake of formatting, generally it's good to use uppercase first letters for your classes so that they're easy to tell apart from variables and class instances.

RagingRoosevelt
  • 2,046
  • 19
  • 34