Data sticking around too long

Matimus mccredie at gmail.com
Thu Sep 7 00:07:34 CEST 2006


Someone correct me if I'm wrong (sometimes I get the terms mixed up)
but I believe that what you are seeing is due to 'number' being an
immutable type. This means that its value cannot be changed and thus
each assignment is effectively creating a new instance if int. I
believe lists are considered immutable also but since it is a container
type it behaves somewhat differently. I read a thread earlier that
addressed a similar issue but I can't find it now. I will post again if
I come accross it. Anyway, as a demonstration try this using python's
command line prompt:

>>> i = int()
>>> j = i
>>> j is i
True
### j and i are attributes that point to the same instance
>>> i = 1
>>> j is i
False
### assignment to I made a new instance and j and i are no longer the
same instance
>>> a = [0,1,2]
>>> b = a
>>> b is a
True
### the same is true for lists
>>> b = [0,1,3]
>>> b is a
False
>>> b = a
>>> b is a
True
### but since 'a' is a container its contents can be modified without
creating a new instance
>>> b[1] = 3
>>> b is a
True
>>> a
[0,3,2]
>>> b
[0,3,2]
>>> a.append(4)
>>> a
[0,3,2,4]
>>> b
[0,3,2,4]
>>> b is a
True

I hope this helps.

-Matt

CedricCicada at gmail.com wrote:
> Greetings again!
>
> There's something more to determining whether a class member is a class
> variable or an instance variable.  Here's a slightly expanded version
> of my last script:
>
> class ScannerCommand:
>     taskName = ''
>     scanList = []
>     number = 0
>
>     def __init__(self, data):
>         pass
> #        self.scanList = []
> #        self.scanList.append(data)
>
> if __name__ == '__main__':
>     c1 = ScannerCommand("c1")
>     c2 = ScannerCommand("c2")
>     c1.number = 1
>     c2.number = 2
>     c1.scanList.append("One")
>     c2.scanList.append("Two")
>     print "C1: " + str(c1.number)
>     for data in c1.scanList:
>         print "   " + data
>     print "C2: " + str(c2.number)
>     for data in c2.scanList:
>         print "   " + data
>
> And here's the output:
> C1: 1
>    One
>    Two
> C2: 2
>    One
>    Two
>
> Here, the two instances share the scanList list, as expected from
> previous discussions, but they have their own copies of the number
> variable.  Why is scanList a class variable but number an instance
> variable here?
>
> Good night, all!
> 
> Rob Richardson
> RAD-CON, Inc.
> Bay Village, OH




More information about the Python-list mailing list