creating class objects inside methods

Carl Banks pavlovevidence at gmail.com
Sun Oct 4 02:03:01 EDT 2009


On Oct 3, 10:12 pm, horos11 <horo... at gmail.com> wrote:
> > >>> a
>
> > <__main__.Myclass instance at 0x95cd3ec>>>> b
>
> > <__main__.Myclass instance at 0x95cd5ac>
>
> > What's the problem?
>
> Like I said, the code was a sample of what I was trying to do, not the
> entire thing.. I just wanted to see if the metaphor was kosher.
>
> It sounds to me from your answer that this is unexpected behavior, so
> I'll go ahead and post the whole thing. My guess is that it is a
> python bug..

Sure.


> Run it (a simple puzzle game solved by breadth first search), and the
> first time state() is called inside the method, it calls __init__.
> Second time, and therafter, it calls __call__. I've highlighted where
> the code fails by putting a pdb.set_trace().
>
> Anyways, I've got a workaround (simply pass in any new objects needed
> from the caller), but it is truly annoying that python is either
> misleading or broken in this way.
>
> Attached find code, does not work vs. 2.6..
[snip]

I don't believe you couldn't reduce that to something simpler.

Anyway, I didn't bother reading all the code or running it, but I had
a suspicion what is was so I looked for it and saw what I was looking
for.

Here's you class statement:


> class state:


Now here's some code that appears much later at the top level:


>     else:
>         seen_states.add(curstate.to_string())
>         for state in curstate.next_states():
>             if not state.to_string() in seen_states:
>                 dq.append(state)
>
>                 print "Trying..\n"
>                 state.print_board()
>                 print "\n"


Whoops.  It looks like you rebound the global variable "state" to a
new value, which makes the class no longer accessible by that name.

My immediate suggestion is to change the name of the class, and to
capitalize the first letter.  "state" is a terrible name for a class.
Class instances, almost by default, maintain state, so naming a class
"state" says almost nothing about what the class is.  Something like
GameState or PlayerState would be better.

Here is some reading material that can help you adjust your coding
style to help avoid such errors in the future:

http://www.python.org/dev/peps/pep-0008


Carl Banks



More information about the Python-list mailing list