在python中阻止作用域 - 它是否类似于函数内部的javascript提升? [英] Block Scoping in python - is it similar to javascript hoisting when inside a function?

查看:54
本文介绍了在python中阻止作用域 - 它是否类似于函数内部的javascript提升?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试理解python中的这段代码

I am currently trying to understand this piece of code in python

def foo(a):
  if a==12:
    var = "Same"
  else:
    var = "different"

我阅读并理解python不支持基于块的范围的事实。因此,在函数内部创建的所有内容(无论是在循环内还是条件语句中)都可以公开地用于函数的其他成员。我还阅读了作用域规则这里。在这一点上,假设这些内部范围变量在函数内被提升就像它们在javascript中被提升一样是否相同?

I read and understand the fact that python does not support block based scoping. So everything created inside a function (whether inside a loop or conditional statements) is openly available to other members of a function.I also read the scoping rules here . At this point would it be same to assume that these inner scoped variables are hoisted inside a functions just like they are hoisted in javascript ?

推荐答案

<你知道了。在函数内部分配的任何名称,未使用 global 显式声明(Py3添加 nonlocal 表示它不在本地范围,但要查看包装范围而不是直接跳到全局范围)是函数开头的局部变量(它在本地数组中保留空间),但在赋值之前读取它会引发 UnboundLocalError

You got it. Any name assigned inside a function that isn't explicitly declared with global (with Py3 adding nonlocal to indicate it's not in local scope, but to look in wrapping scopes rather than jumping straight to global scope) is a local variable from the beginning of the function (it has space reserved in an array of locals), but reading it prior to assignment raises UnboundLocalError.

这篇关于在python中阻止作用域 - 它是否类似于函数内部的javascript提升?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆