Scope of a class..help???

Tim Roberts timr at probo.com
Fri May 24 01:05:57 EDT 2013


lokeshkoppaka at gmail.com wrote:
>
>ok Peter Otten,
>but how to make a Class global??

Your class IS global.  I still don't think you understand what you did
wrong.  You've tripped into a strange little quirk of scoping.  Here is
your code with some unimportant lines removes.

class Node:
    def __init__(self, value=None):
        self.value = value
        self.next = None

## OK, at this point, you have a global called "Node", which is a class.

def number_to_LinkedList(numbers):
      pass
      list_numbers = list(numbers)
      head_node = Node()
      # ... 
      current_node.next = None
      while Node:
        print Node.data

Python actually does a first scan through your function before it starts to
compile it.  When it does the scan, it sees you use the name "Node" as a
local variable.  At that point, it remembers that "in this function scope,
'Node' is a local name".  Now, it codes to compile the class.  When it
encounters Node() for the first time, it sees that "Node" is not defined
locally, even though it was supposed to be a local name.

You are assuming that the first Node() in that function will automatically
refer to the global class.  It won't.  The only way to solve this dilemma
is to change the name you use in the "while" loop.
-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.



More information about the Python-list mailing list