class members vs instance members

hdixon huwdixon at netrox.net
Sun Jul 9 11:35:49 EDT 2006


Ive spent a few days going thru a couple of Python tutorials. No
problem until I got to classes. I guess my java mindset is blocking my
vision. I've borrowed another thread's code snippet and cannot explain
the results:
class MyClass:
    list = []
    myvar = 10

    def add(self, x):
        self.list.append(x)
        self.myvar = x

    def printer(self):
        print self.list
        print self.myvar

a = MyClass()
b = MyClass()

for n in range(20):
    a.add(n)

print "list in a:"
a.printer()
print "list in b:"
b.printer()

This produces:
list in a:
list in a:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
19
list in b:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
10

WHY do the "class members" list and myvar seem to behave differently?
Given the way that list[] is supposedly shared why doesnt myvar exhibit
the same behavior? It seems that myvar is acting like a true "instance
member". Is this simply because of the underlying types?


TIA




More information about the Python-list mailing list