confused by bindings
Don O'Donnell
donod at home.com
Wed Sep 19 15:16:23 EDT 2001
Sam Falkner wrote:
>
> I'm confused. I'm a relative newbie, but am still surprised that I
> can't make this work.
>
> 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:
>
> --- file data.py ---
>
> class Cell:
> count = 0
> def __init__(self, stuff):
> self.count += 1
> self.stuff = stuff
> print 'count is', self.count
>
> --- file test.py ---
>
> class CellTestCase(unittest.TestCase):
> def testforleaks(self):
> data.Cell.count = 0
> # do a whole bunch of stuff
> # x = a gnarly collection of Cell objects
> # count number of Cell objects in x
> self.failUnlessEqual(count-of-Cells-from-x, data.Cell.count)
>
> In other words, I'm trying to test for a leak of Cell objects. But,
> no matter what I've tried, this doesn't work. I've tried
> global-to-the-data-module variables for the count, I've tried the Borg
> pattern from the cookbook, but nothing works.
>
> When I run it this way, I get
> count is 1
> count is 1
> count is 1
> count is 1
> ...
>
> and the test fails with 5499 != 0.
>
> Okay, I feel stupid here. What am I doing wrong?
>
> Thanks!
>
> - Sam
Hi Sam,
Not stupid, just confusing instance variables with class variables. The
argument 'self' in your __init__ method refers to the class *instance*
that is being initialized, so that the statement self.count += 1 in
Cell.__init__ is really incrementing the new instance variable named
count. Here's how that statement works:
1. Looks for a variable named count in the dictionary of the new
instance.
2. Doesn't find it, so searches the Cell class dictionary.
3. Finds it, with a value of 0.
4. Adds 1 to it.
5. Stores it in the local instance dict.
So every instance you create will have a count value of 1, as you
noticed.
What you need to do to maintain an instance counter by incrementing the
class variable directly. Your class definition should look like this:
>>> class Cell:
count = 0
def __init__(self, stuff):
Cell.count += 1
self.stuff = stuff
print 'count is', Cell.count
>>> x = []
>>> x.append(Cell('a'))
count is 1
>>> x.append(Cell('b'))
count is 2
>>> x.append(Cell('c'))
count is 3
>>> Cell.count
3
To be complete, you should also define a __del__ method in your Cell
class which will decrement Cell.count when an instance is deleted:
def __del__(self):
Cell.count -= 1
Hope this helps.
Cheers,
Don
More information about the Python-list
mailing list