confused by bindings

Chris Barker chrishbarker at home.net
Wed Sep 19 15:17:42 EDT 2001


Sam Falkner wrote:

> What I want to do is to have my test module set "stuff" in one of the
> other modules, do its tests, and then check the results.  Code might
> be more clear:

In general, it is, but it helps a lot if it is working code (or, in this
case, broken code that runs)
 
A) count-of-Cells-from-x is not a legal variable name so I get a syntax
error (no "-" are allowed in variable names

B) you should probably provide a shortened version of:
# do a whole bunch of stuff
# x = a gnarly collection of Cell objects
# count number of Cell objects in x
 
That does something

C) I'm betting that this could all be in one file and exhibit the same
symptoms, so you can make an easy test case.

D) All that being said, I can take a guess at what you are trying to do:
you want a class attribute, count, that is increased every time an
instance is created.

The way you have it written, Cell.count is a reference to the object, 0.
At each instance creation you now point the instance variable,
self.count to a new object, 1 (0+1). the original Cell.count is still
pointing to the original 0. (I know I havn't explained this very well.
search the archives, there was an involved discussion about this a month
or so ago.


The solutions:

A) You can use an immutable type for count, so that you can change it's
contents, rather than creating a new one:

class Cell:
    count = [0]
    def __init__(self):
        self.count[0] += 1
        print 'count is', self.count

a = Cell()
b = Cell()
c = Cell()
d = Cell()
e = Cell()

# this works, but note that when you delete a few of these instances,
the count isnot affected:
del a,b,c

f = Cell()

# so you have a count of how many are created, not how many currently
exist.

Another option is to reference the attribute of the Cell class directly:

class Cell2:
    count = 0
    def __init__(self):
        Cell2.count += 1
        print 'count is', Cell2.count


a = Cell2()
b = Cell2()
c = Cell2()
d = Cell2()
e = Cell2()



-- 
Christopher Barker,
Ph.D.                                                           
ChrisHBarker at home.net                 ---           ---           ---
http://members.home.net/barkerlohmann ---@@       -----@@       -----@@
                                   ------@@@     ------@@@     ------@@@
Oil Spill Modeling                ------   @    ------   @   ------   @
Water Resources Engineering       -------      ---------     --------    
Coastal and Fluvial Hydrodynamics --------------------------------------
------------------------------------------------------------------------



More information about the Python-list mailing list