首页 > Python作用域的问题

Python作用域的问题

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


你的代码,我在解释器和 PyCharm 里执行了都没有看到你说的问题。最好把执行的代码也贴出来,只看这些我也没看出有问题。


python的变量作用域:
模块对应global,
最内层为local,
外层为nonlocal
变量查找顺序:内层作用域->外层->全局->builtin
只有class、def和lamda会改变作用域

读取变量的时候,如果local没有,查找nonlocal,然后global
写变量的时候,如果没有指明nonlocal/global, 就是在局部作用域定义一个新的变量
下面的例子摘自python tutorial第9章

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)
【热门文章】
【热门文章】