gomfy
gomfy

Reputation: 689

Create object list with for loop (python)

The following code:

#!/usr/bin/python

class TestClass:
    container = []

testList = []

for i in range(2) :
    testList.append(TestClass())
    for j in range(4) :
        testList[i].container.append(j)

for i in range(2):
    print testList[i].container

returns the following:

[0, 1, 2, 3, 0, 1, 2, 3]
[0, 1, 2, 3, 0, 1, 2, 3]

I'm puzzled as to why... I would expect it to be:

[0, 1, 2, 3]
[0, 1, 2, 3]

Can someone help me what I'm missing here? I'm new to python I have a C/C++ background. Thanks a lot!

Upvotes: 2

Views: 910

Answers (1)

abarnert
abarnert

Reputation: 365637

That's not how you do members in Python.

Or, rather, it's how you do it when you want a class attribute: Instead of each TestClass instance having its own separate container member, they all share a single one. (Since you mentioned your C++ background, this is similar to a static member in C++, although not quite identical, so don't try to take that analogy too far.)

That's not what you want here; you want an instance attribute. The normal way to do that is to just create one in the __init__ method (which is like the C++ constructor—although, again, not exactly like it):

class TestClass:
    def __init__(self):
        self.container = []

And yes, this means that if you really want to, you can create two different TestClass instances that, despite being the same type, have completely different members.

While we're at it, in Python 2.x, you never* want to write class TestClass:. Use class TestClass(object): instead.

You probably want to read through the Classes chapter of the official tutorial, or some equivalent explanation elsewhere. Python classes are very different from C++ classes in a lot of ways.


* There are some exceptions where you at least arguably want it, but you don't want to learn about those now.

Upvotes: 4

Related Questions