简体   繁体   English

封闭的局部范围内的变量与全局范围内的变量-Python

[英]Variable in enclosed local scope vs variable in global scope - Python

hi guys I can't figure out why when find_average() is called, total = 20 in the global scope is being used for the find_total() function, instead of total = 10 in the enclosing scope? 嗨,大家好,我不知道为什么在find_average()时,将find_total()函数的全局范围内的total = 20而不是封闭范围内的total = 10 Thanks in advance for any insights and help! 预先感谢您的任何见解和帮助!

total = 20

def find_total(l):
    return total

def find_length(l):
    length = len(l)
    return length

def find_average(l):
    total = 10
    return find_total(l) / find_length(l)


average = find_average(example_list)

Each function has its own scope. 每个功能都有其自己的范围。 It starts at the functions local, inner scope, then goes outwards through enclosing functions until it reaches global (module) scope. 它从局部,内部范围的函数开始,然后通过封闭的函数向外扩展,直到到达全局(模块)范围。 This sequence depends on the scope the function is defined in . 此顺序取决于在中定义函数的范围。 The stack (calling sequence) is not used for variable lookup. 堆栈(调用序列) 用于变量查找。

In your example, each function only has its inner scope followed by the outer scope. 在您的示例中,每个函数只有其内部作用域,然后是外部作用域。 For find_total , that's <module>.find_total.<locals> and <module> . 对于find_total ,这是<module>.find_total.<locals><module> So, whenever find_total is run, it will look up total in its local scope, failing, and look in the global scope. 因此,每当运行find_total ,它将在其本地范围内查找total ,失败并在全局范围内查找。 There, total == 20 . 在那里, total == 20

The scope inside find_average is exclusive to find_average . 内的范围find_average是独家find_average Neither global scope, find_total or find_length can access it. 全局范围, find_totalfind_length无法访问它。 If you want to pass something from inside find_average to find_total , you should do so via a parameter. 如果要从find_average内部将某些内容find_averagefind_total ,则应通过参数进行传递。


Alternatively, if find_total can be defined inside find_average . 可选地,如果find_total可以内部限定find_average This way, find_total resolves names by searching the sequence <module>.find_average.<locals>.find_total.<locals> -> <module>.find_average.<locals> -> <module> . 这样, find_total通过搜索序列<module>.find_average.<locals>.find_total.<locals> -> <module>.find_average.<locals> -> <module> find_total解析名称。

total = 20

def find_length(l):
  length = len(l)
  return length

def find_average(l):
  total = 10
  def find_total(l):
    return total
  return find_total(l) / find_length(l)

 average = find_average(example_list)

This will make find_total inaccessible from outside find_average ! 这将使find_total从外部find_average 无法访问

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM