Help! This is driving me insane!

Bengt Richter bokr at oz.net
Thu Sep 26 22:53:55 EDT 2002


On Thu, 26 Sep 2002 23:43:33 GMT, "kara.klosterman" <kara.klosterman at attbi.com> wrote:

>Hello,
>I created a very simple class that totals some data
>but I am not getting the output from it that I would
>expect at all.
>Here is the class:
>http://www.geocities.com/dbasch/insane.txt
>
>I would expect to get:
>[0, 0]
>[0, 0]
>[[0, 0]]
>
Why?

>but I am getting:
>[0, 0]      <<--(a)
>[0, 0]      <<--(b)
>[[1, 1]]    <<--(c)
>
Why not? [I labeled the above (a) etc. for reference below].

>I dont understand how the 'grouptotals' list is
>getting the incremented values prior to the
>'grouptotalcounter' function being called.
What makes you think it is? The value you printed at (b) shows it's not.

>furthermore, I can place a 'print grouptotals' right
>after the errorlog append and it isnt the incremented
>values! Please tell me this isnt a normal thing!

Did you walk through the code and think through what
is happening?

class Test:
    def __init__(self):
        self.errorlog = []        
        pass

    def run(self):
        self.grouptotals = []
        for x in range(2):
            self.grouptotals.append(0)
            
        print self.grouptotals                    <<--(a), should be [0, 0]
        self.errorlog.append(self.grouptotals)    <<-- self.errorlog now [[0, 0]]
        print self.grouptotals                    <<--(b), no change, still [0, 0]
            
        self.grouptotalcounter()                  <<-- self.grouptotals changed to [1, 1]
                                                      (note that self.errorlog still refers to
                                                       the now changed self.grouptotals)
        
        return self.errorlog                      <<-- ref to changed grouptotals makes it [[1, 1]]
                                                  but there is no print statement. Reference to
                                                  self.errorlog is returned to caller (d) below
                                                  of the run method.

    def grouptotalcounter(self):
        for totalbyindex in range(2):
            self.grouptotals[totalbyindex] += 1   <<-- [0, 0] becomes [1, 1] here


If you put the above in insane.py and interactively made an instance thus:

 >>> import insane
 >>> t=insane.Test()
 >>> t.run()               # <<--(d)
 [0, 0]
 [0, 0]
 [[1, 1]]

that last line is the return value from t.run() being printed by the interactive
eval/print loop.

Everything as one would expect from the code.

Regards,
Bengt Richter



More information about the Python-list mailing list