Python作用域的问题
ringa_lee
ringa_lee 2017-04-17 17:31:38
[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

ringa_lee
ringa_lee

ringa_lee

全部回复(2)
伊谢尔伦

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)
PHPz

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号