Image

Please help before I lose more sleep!

Hi there,
Thanks for your input with my last request. Seeing the original code was borrowed I decided to rework it with a more fluid design, however the following simplified version puzzles me. Can someone please explain to me why "z" is populating cross instances of the same class. I have been banging my head against the wall for days on this and I don't think I know enough about python to explain it happening. I realize that this is bad design, but it is obviously doing this for a reason. And well I'd really like to know the reason ( so I can avoid it in the future :)

Not only does z save state between instances. It's also changing the attribute of the original instance like they are sharing the same memory place. Well that must be what is happening. So I know how to replicate it, and I know how to not replicate... I just understand why. at will...



passes = 0

class klass:
    def enclosing(self,x):
        self.results = self.anomaly(x)

    def anomaly(self,x,y=1,z=[]):
        global passes
        print 'Pass number', passes
        print 'x', x
        print 'y', y
        print 'z', z
        z.append([x,y])
        passes += 1
        if passes < 3:
            z = self.anomaly(2,2,z)
        return z


a = klass()
b = klass()

print 'Running a...'
a.enclosing(1)
print 'a.results: ', a.results

print 'Running b...'
b.enclosing(4)
print 'a.results: ', a.results
print 'b.results: ', b.results

## output

Running a...
Pass number 0
x 1
y 1
z []
Pass number 1
x 2
y 2
z [[1, 1]]
Pass number 2
x 2
y 2
z [[1, 1], [2, 2]]
a.results:  [[1, 1], [2, 2], [2, 2]]
Running b...
Pass number 3
x 4
y 1
z [[1, 1], [2, 2], [2, 2]]
a.results:  [[1, 1], [2, 2], [2, 2], [4, 1]]
b.results:  [[1, 1], [2, 2], [2, 2], [4, 1]]







PS: I'm running a 2.2.3 interpretor if that makes a different.