Python作用域的问题
ringa_lee
ringa_lee 2017-04-17 17:31:38
0
2
289
class Node(object):
    def __init__(self, data=None, next_=None):
        self.next_ = next_
        self.data = data

class LinkList(object):
    def __init__(self):
        self.head = None
        self.tear = None
    def insert(self, node):
        if self.head is None:
            # print("is None")
            self.head = node
            self.tear = node
            self.head.next_ = self.tear
        else:
            # print("tear")
            self.tear.next_ = node
            self.tear = node
    def display(self):
        # global node
        node = self.head
        if node is not None:
            print(node.data)
            node = node.next_

为了便于理解我把整段代码都贴上来了.
这是用Python实现链表的插入功能

问题出在LinkList类中的display()函数
不把变量node设置为global的话,if语句下面node = node.next_这句 ,被赋值的node是一个新的变量(PyCharm提示Shadows name 'node' from outer scope和Local variable 'node' value is not used)

如果把if语句改为while循环,if和display函数下面的node就都为同一个变量

请问问题出在哪里 ?
Python版本是3.5

ringa_lee
ringa_lee

ringa_lee

reply all(2)
伊谢尔伦

Python's variable scope:
The module corresponds to global,
The innermost layer is local,
The outer layer is nonlocal
The variable search order: inner scope ->outer layer->global->builtin
only class, def and lamda will change the scope

When reading a variable, if local does not exist, search for nonlocal, then global
When writing a variable, if nonlocal/global is not specified, a new variable is defined in the local scope
The following example is taken from Chapter 9 of the python tutorial

def scope_test():
    def do_local():
        spam = "local spam"
    def do_nonlocal():
        nonlocal spam
        spam = "nonlocal spam"
    def do_global():
        global spam
        spam = "global spam"
    spam = "test spam"
    do_local()
    print("After local assignment:", spam)
    do_nonlocal()
    print("After nonlocal assignment:", spam)
    do_global()
    print("After global assignment:", spam)

scope_test()
print("In global scope:", spam)
PHPzhong

I have executed your code in the interpreter and PyCharm and haven’t seen the problem you mentioned. It's best to post the executed code as well. I don't see any problems just by looking at these.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template