Python作用域的问题

 荣哥918 发布于 2022-10-29 14:25
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

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

    2022-10-31 01:08 回答
  • 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)
    
    2022-10-31 01:08 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有