confused by bindings

Mitchell Morris mitchell.morris at cingular.com
Wed Sep 19 14:20:10 EDT 2001


Sam Falkner <samf+usenet at frii.com> wrote in 
news:ii7k7yvqi87.fsf at central.sun.com:

> 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

Well, I learn something new every day. I would have expected this to raise a  
NameError on the "self.count += 1" line. It doesn't though ... I'll have to 
revisit my understanding of scoping now.

The short answer is that "self.count" isn't bound to the same thing as 
"Cell.count". "self.count" is an attribute of the instance: each new Cell 
instance gets its own copy. If you want to manipulate the class attribute, 
then you have to say so via "Cell.count += 1" instead.


[snip]
> Okay, I feel stupid here.  What am I doing wrong?

My guess is you're still wearing your Java hat, but I'm not entirely sure.

> Thanks!
> 
> - Sam

so-much-for-my-resolve-not-to-followup-on-Usenet-any-more-ly y'rs
+Mitchell



More information about the Python-list mailing list