Newbie NameError problem

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Wed Dec 12 12:24:21 EST 2007


MartinRinehart at gmail.com a écrit :
> I don't understand what I don't understand in the following:

You already have the answer (hint: a Python module is sequentially 
executed when loaded by the interpreter)

Just a couple side notes:

  > # but I need locations, so this is impure, 11-line, Python:
> 
> line_ptr = 0
> for line in text:
>     output = ''
>     char_ptr = 0
> 
>     for char in line:
>         output += char
>         char_ptr += 1
> 
>     print output,
>     line_ptr += 1


Use enumerate and a for loop.

for line_ptr, line in enumerate(text):
   for char_ptr, char in enumerate(line):
      print "char %s of line %s is %s" % (char_ptr, line_ptr, char)

> # with a Loc object, 10 lines (not counting the Loc class):
> 
> loc = Loc(0,0) # Name error: name 'Loc' is not defined

Indeed. It is not yet defined at this time. Remember that in Python, 
almost everything happens at runtime.


(snip)

I think you're going to have a hard time if you don't read about 
Python's object model...

> class Loc:

Better to use new-style classes unless you have compelling reasons to 
stick with the very outdated 'classic' model.

class Loc(object):

>     line = 0
>     char = 0

This define two class attributes - that is, attributes that are members 
of the Loc class object (*not* Loc instances), and so are shared by all 
instances. This is probably not what you want.

>     def __init__(self, l, c):
>         line = l
>         char = c

This defines two local variables line and char, bind them to resp. l and 
c, then returns - discarding locals of course.

The use of 'self' is *not* optional in Python. Within the function, it's 
a reference to the current instance. If you want to define instance 
attributes, you have to set these attributes on the current instance.

def __init__(self, line, char):
   self.line = line
   self.char = char

>     def nextChar(self):
>         char += 1

NameError here. You want self.char

>     def nextLine(self):
>         line += 1

NameError here. You want self.line

>         char = 0

Local variable, discarded when exiting the function. You want self.char

>     def repr(self):
>         return 'Loc: line='+str(line)+', char='+str(char)

NameError * 2, etc...

Also, Python has string formatting:

       def __repr__(self):
           return "<Loc: line=%s - char=%s>" % (self.line, self.char)

HTH



More information about the Python-list mailing list