Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

python - 在函数中使用全局变量(Using global variables in a function)

How can I create or use a global variable in a function?

(如何在函数中创建或使用全局变量?)

If I create a global variable in one function, how can I use that global variable in another function?

(如果在一个函数中创建全局变量,如何在另一个函数中使用该全局变量?)

Do I need to store the global variable in a local variable of the function which needs its access?

(我是否需要将全局变量存储在需要对其进行访问的函数的局部变量中?)

  ask by user46646 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use a global variable in other functions by declaring it as global in each function that assigns to it:

(您可以通过声明为使用其他功能的全局变量global指派每个功能吧:)

globvar = 0

def set_globvar_to_one():
    global globvar    # Needed to modify global copy of globvar
    globvar = 1

def print_globvar():
    print(globvar)     # No need for global declaration to read value of globvar

set_globvar_to_one()
print_globvar()       # Prints 1

I imagine the reason for it is that, since global variables are so dangerous, Python wants to make sure that you really know that's what you're playing with by explicitly requiring the global keyword.

(我想这是因为全局变量是如此危险,Python希望通过显式要求使用global关键字来确保您真正知道这就是要使用的内容。)

See other answers if you want to share a global variable across modules.

(如果要在模块之间共享全局变量,请参见其他答案。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...