简单的Python变量范围

Wil*_*ild 0 python

在我看来,函数可以引用其范围之外的变量,但不能设置它们.它是否正确?我明白了吗?

我还包括全局变量用法.我知道他们是糟糕的ju-ju并会避开它们; 我知道如何解决这个问题,但只是想明确一点.

我的示例程序:

import foo

# beginning of functions

# this one works because I look at the variable but dont modify it
def do_something_working:

    if flag_to_do_something:
          print "I did it"

# this one does not work because I modify the var
def do_something_not_working:

    if flag_to_do_something:
          print "I did it"
          flag_to_do_something = 0

# this one works, but if I do this God kills a kitten
def do_something_using_globals_working_bad_ju_ju:

    global flag_to_do_something

    if flag_to_do_something:
         print "I did it"
         flag_to_do_something = 0


# end of functions

flag_to_do_something = 1

do_something_working()
do_something_not_working()
do_something_using_globals_working_bad_ju_ju()
Run Code Online (Sandbox Code Playgroud)

Blu*_*ers 5

正确.好吧,大多数 当您flag_to_do_something = 0不修改变量时,您正在创建一个新变量.的flag_to_do_something是在功能创建的将是一个单独的链路(在这种情况下)相同的对象.但是,如果您使用了修改变量的函数或运算符,那么代码就可以工作了.

例:

g = [1,2,3]
def a():
    g = [1,2]
a()
print g #outputs [1,2,3]

g = [1,2,3]
def b():
    g.remove(3)
b()
print g #outputs [1,2]
Run Code Online (Sandbox Code Playgroud)