栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

为什么Python中的函数可以在封闭范围内打印变量,但不能在赋值中使用它们?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

为什么Python中的函数可以在封闭范围内打印变量,但不能在赋值中使用它们?

类和函数是不同的,类内部的变量实际上是作为其属性分配给类的名称空间的,而在函数内部,变量只是不能在其外部访问的普通变量。

实际上,函数内部的局部变量是在首次解析该函数​​时确定的,并且python不会在全局范围内搜索它们,因为它知道您已将其声明为局部变量。

因此,一旦python看到

x = x + 1
(赋值)并且没有
global
为该变量声明,那么python将不会在全局或其他范围内寻找该变量。

>>> x = 'outer'>>> def func():...     x = 'inner'  #x is a local variable now...     print x...     >>> func()inner

常见陷阱:

>>> x = 'outer'>>> def func():...     print x       #this won't access the global `x`...     x = 'inner'   #`x` is a local variable...     print x...     >>> func()...UnboundLocalError: local variable 'x' referenced before assignment

但是,当您使用一条

global
语句时,则使用python在
global
范围内查找该变量。

阅读:当变量具有值时,为什么会收到UnboundLocalError?

nonlocal
:对于嵌套函数,您可以使用
nonlocal
py3.x中的语句修改在封闭函数中声明的变量。


但是类的工作方式不同,实际上

x
在类内部声明的变量
A
变为
A.x

>>> x = 'outer'>>> class A:...    x += 'inside'  #use the value of global `x` to create a new attribute `A.x`...    print x        #prints `A.x`...     outerinside>>> print xouter

您还可以直接从全局范围访问类属性:

>>> A.x'outerinside'

global
在课堂上使用:

>>> x = 'outer'>>> class A:...     global x...     x += 'inner' #now x is not a class attribute, you just modified the global x...     print x...     outerinner>>> x'outerinner'>>> A.xAttributeError: class A has no attribute 'x'

函数的陷阱不会在类中引发错误:

>>> x = 'outer'>>> class A:...     print x#fetch from globals or builitns...     x = 'I am a class attribute' #declare a class attribute...     print x#print class attribute, i.e `A.x`...     outerI am a class attribute>>> x'outer'>>> A.x'I am a class attribute'

LEGB 规则:如果没有

global
nonlocal
被使用,则蟒蛇搜索顺序。

>>> outer = 'global'>>> def func():        enclosing = 'enclosing'        def inner():     inner = 'inner'     print inner#fetch from (L)ocal scope     print enclosing       #fetch from (E)nclosing scope     print outer#fetch from (G)lobal scope     print any  #fetch from (B)uilt-ins        inner()...         >>> func()innerenclosingglobal<built-in function any>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/639099.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号