By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
439,985 Members | 1,575 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 439,985 IT Pros & Developers. It's quick & easy.

Magic class member variable initialization with lists

P: n/a
Hi, I reported a bug to the bugtracker (issue 1443), but it was
rejected with the comment:

"Go ask on c.l.py why this is not a bug"

After decrypting c.l.py to the name of this group, I'll do as I was
told so nicely, because I really think it is a misconcept, and cost me
two days because I couldn't believe it.

So here's the problem:
The Initialization of member variables with lists leads to strange
behavior.

The member variable is common to each instance of a class, if the
datatype is a list-Object (and presumable any other PyObject)

Example:
#-------------------------------------------------------
class Proof:
a=[]
b=[]

def __init__(self):
print self.a, self.b, self
self.a.append("STICKYARRAY")
self.b=["NONSTICKY ASSIGN"]

if __name__ == "__main__":
p1=Proof()
p2=Proof()
#-------------------------------------------------------

The execution of this results in:
>[] [] <__main__.Proof instance at 0x00BA7120>
['STICKYARRAY'] [] <__main__.Proof instance at 0x00BA7148>
So the initialized list a is the same in both instances, but they are
completely different objects.

Well, I can think of the coders problem, that when creating the
object, always the same copy of the list object is being taken which
has once been defined, but it doesn't makes sense, because they are
not really static like C++, because as soon as you reassign them, they
are lost.

Bye,
Neo
Nov 15 '07 #1
Share this Question
Share on Google+
1 Reply


P: n/a
This is the expected behaviour. The reference on classes (http://
docs.python.org/ref/class.html) says:
Variables defined in the class definition are class variables;
they are shared by all instances. To define instance variables,
they must be given a value in the __init__() method or in
another method. Both class and instance variables are
accessible through the notation ``self.name'', and an instance
variable hides a class variable with the same name when
accessed in this way.
In your example, 'a' is a class variable, so it's shared by all
instances. 'b' is also a class variable, but in the __init__ method
you create an instance variable with the same name 'b', which takes
precedence over the class-level variable, so 'b' isn't shared.

I think what you need is:

class Proof:
def __init__(self):
self.a = []
self.b = []
# other things

Regards,
Marek
Nov 15 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.