为什么一个变量是全局访问的

为什么一个变量是全局访问的

本文介绍了为什么一个变量是全局访问的,而另一个不是在Python中访问的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个简单的BFS代码.

I am trying to implement a simple BFS code.

代码:

def initalizeVertex():
    n = int(input('Enter the no. of vertices.\n'))
    for vertex in range(n):
        Vertex.append(vertex)
        node_adjacency[vertex] = []

def initalizeUndirectedEdges():
    n = int(input("Enter the no. of edges.\n"))
    print("Enter the space seperated edges.")
    for i in range(n):
        a,b = map(int,input().split())
        node_adjacency[a].append(b)
        node_adjacency[b].append(a)

def bfs():
    current_level = 1
    print(Vertex)
    while(current_level_nodes):
        for current_node in current_level_nodes:
            for child_node in node_adjacency[current_node]:
                if node_parent.get(child_node) == None:
                   node_parent[child_node] = current_node
                   next_level_nodes.append(child_node)
                   node_level[child_node] = current_level
        current_level_nodes = [node for node in next_level_nodes]
        next_level_nodes = []
        current_level += 1
    print(node_level)
    print(node_parent)

def printData():
    print(Vertex)
    print(node_adjacency)
    print(node_parent)
    print(node_level)
    print(current_level_nodes)
    print(next_level_nodes)


if __name__ == "__main__":
    root = 0
    Vertex = []
    node_adjacency = {}
    node_parent = {root:None}
    node_level = {root:0}
    current_level_nodes = [root]
    next_level_nodes = []

    initalizeVertex()
    initalizeUndirectedEdges()

    printData()
    bfs()

代码输出为:

此代码给我错误:

in bfs
    while(current_level_nodes):
UnboundLocalError: local variable 'current_level_nodes' referenced before assignment

很显然, bfs()函数无法访问列表 current_level_nodes .我可以通过将列表 current_level_nodes 传递给 bfs 函数来解决此问题.

Clearly, the bfs() function cannot access the list current_level_nodes. I can solve this by passing the list current_level_nodes to the bfs function.

但是,我的问题是为什么当我没有将列表 Vertex 传递给 initalizeVertex()函数,该函数仍可以访问和修改它吗?

But, my question is why do I have to pass this list to bfs() function when I haven't passed the list Vertex to initalizeVertex() function and the function could still access and modify it?

我还没有将任何参数传递给 printData 函数,但是该函数会打印所有列表和字典,而不会给出任何错误.

Also I haven't passed any parameter to printData function but that function prints all the lists and dictionaries without giving any error.

推荐答案

Python会尝试在本地范围1st处查找变量.如果在本地找不到它们,Python将在全球范围内寻找它们.

Python will try to look for the variable at local scope 1st. If they're not found locally, Python will look for them globally.

例如-

在您的printData()函数中-Python将尝试在本地查找变量,但此方法未定义任何变量.因此,Python将进入全球范围.它会选择值并打印出来.

In your printData() function -Python will try to look for the variables locally, but no variables are defined in this method. So, Python will go at the global scope. It'll pick the values and will print them.

def printData():
    print(Vertex)
    print(node_adjacency)
    print(node_parent)
    print(node_level)
    print(current_level_nodes)
    print(next_level_nodes)

在另一个函数bfs()-

In another function bfs() -

Python将在一段时间内看到current_level_nodes,Python将尝试查找定义变量的位置.在这里,事情变得棘手,因为您稍后在函数中分配了相同的变量.这会混淆Python,并且会引发错误.

Python will see current_level_nodes inside a while, and Python will try to find where the variable is defined. Here things will get tricky as you've assigned the same variable in the function later. This will confuse Python, and it'll throw the error.

line 1. - while(current_level_nodes):
line 2. - current_level_nodes = [node for node in next_level_nodes]

这就是为什么您需要明确告诉Python您要使用全局变量的原因-

That's why you need to explicitly tell Python that you want to use global variable -

global current_level_nodes

这篇关于为什么一个变量是全局访问的,而另一个不是在Python中访问的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 01:26