2

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!

asked Apr 17, 2015 at 4:45
1
  • 1
    The reason is that TestClass.container is a class attribute, not an instance attribute. Define container in the constructor. Commented Apr 17, 2015 at 4:48

1 Answer 1

4

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.

answered Apr 17, 2015 at 4:48
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.