Newbie NameError problem

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Wed Dec 12 17:10:45 EST 2007


MartinRinehart at gmail.com a écrit :
> Thanks to all!
> 
> I will put my class defs first (tho not without expressing my
> disappointment that this is required in a late 20th century language);

That's because you dont get the "execution model" of Python.

First point, remember that Python in Python everything is an object - 
including classes and functions.

Now a Python module is a list of statements, and all these statements (I 
mean, the ones at the top-level of the module) are executed sequentially 
when the module is loaded. The def and class statements actually 
*define* corresponding names in the defining namespace - and of course 
bind the newly created function or class objects to these names. So you 
can see def and class statements as name-binding (IOW: assignement) 
operations.

So indeed, until the def or class statement has been fully executed, the 
  corresponding object doesn't exist, and can't obviously be bound to a 
name.

Would you expect the following code to work ?

# dumb.py
print foo
foo = 42

If you understand that the class statement is to be read as a convenient 
shortcut for an operation that otherwise looks like:

ClassName = some_call_that_creates_a_class_object(all_required_params)

you understand why you cannot expect to use class ClassName before this 
statement has been executed.

Now this is seldom a problem since - except perhaps for trivial scripts 
- one usually put the effective code in functions. Python is not a 
"better bash" - it's really a full-blown application programming 
language that *also* happen to be usable for scripting.

> learn about enumerate as it looks like exactly what I need and discard
> my C++/Java based object model because this is a totally other thing.
> 
> If someone who knows both object models would comment on Python's
> model v. C++/Java's model that would be helpful.

There have been a couple posts here about Python's object model recently 
IIRC. But anyway, starting with the online tutorial, then reading the 
doc section about new-style classes should be a good start. If you have 
questions then, please post here.



More information about the Python-list mailing list