Laz*_*rks 1 python global-variables local-variables
好的,下面的代码是完全废弃的,我编写的无意义代码; 但是我觉得奇怪的是我可以从qwerty()函数访问变量"b",而b只是在里面声明了......我想我只能在某种程度上以全局方式声明它才能访问它?
x = 14
while (x > 10):
b = 3
b += 3
print(b)
x -= 1
def qwerty():
if b == 6:
print("b can be accessed elsewhere?")
input("")
Run Code Online (Sandbox Code Playgroud)
运行此代码,"b可以在其他地方访问吗?" 将打印...即使b == 6引用在单独的while()函数中声明的变量b.
我想我仍然对python中全局变量和局部变量的属性感到困惑.谁能解释为什么会发生这种情况?
while不是一个功能.创建自己的作用域的唯一结构是def,class和发电机表达式/内涵(取决于版本).
if True:
while 1:
for x in range(1):
z = 1
break
def function():
print(z)
function() # prints 1
Run Code Online (Sandbox Code Playgroud)
这与内部函数的工作方式几乎相同.
def function():
while True:
x = 5
break
def nested():
print(x)
nested() # prints 5
x = 10
nested() # prints 10
Run Code Online (Sandbox Code Playgroud)
我说几乎是因为根据它们是全局变量还是属于封闭函数,你可以修改外部变量有一些细微的差别.
| 归档时间: |
|
| 查看次数: |
132 次 |
| 最近记录: |