Top.Mail.Ru
Python
? ?
LiveJournal for python.
View:Personal Journal.
View:Friends.
View:Calendar.
Missed some entries? Then simply jump to the previous day or the next day.

Wednesday, May 26th, 2004

Subject:Please help before I lose more sleep!
Time:10:59 pm.
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
outputCollapse )





PS: I'm running a 2.2.3 interpretor if that makes a different.
Comments: Read 11 orAdd Your Own.

LiveJournal for python.

View:User Info.
View:Friends.
View:Calendar.
View:Memories.
Missed some entries? Then simply jump to the previous day or the next day.

Image