python 蟒蛇| 脚本执行后如何使局部变量成为全局变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1579996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python | How to make local variable global, after script execution
提问by frank
Here is the code. What I need to do is find a way to make i
global so that upon repeated executions the value of i
will increment by 1 instead of being reset to 0 everytime. The code in main
is from another script that I embed in 'main' in order to have the trace function work. This is all being done from Java.
这是代码。我需要做的是找到一种方法来使i
全局化,以便在重复执行时, 的值i
将增加 1 而不是每次都重置为 0。中的代码main
来自我嵌入到“main”中的另一个脚本,以便跟踪功能正常工作。这一切都是从 Java 完成的。
from __future__ import nested_scopes
import sys
import time
startTime = time.time()
timeLimit = 5000
def traceit(frame, event, arg):
if event == "line":
elapsedTime = ((time.time() - startTime)*1000)
if elapsedTime > timeLimit:
raise Exception, "The execution time has exceeded the time limit of " + str(timeLimit) + " milliseconds. Script will now terminate"
return traceit
sys.settrace(traceit)
def main______():
try:
i+=1
except NameError:
i=1
main______()
回答by Robert Rossney
It's unfortunate that you've edited the question so heavily that peoples' answers to it appear nonsensical.
不幸的是,您对问题进行了如此大量的编辑,以至于人们对它的回答显得毫无意义。
There are numerous ways to create a variable scoped within a function whose value remains unchanged from call to call. All of them take advantage of the fact that functions are first-class objects, which means that they can have attributes. For instance:
有多种方法可以在函数内创建作用域变量,该变量的值在调用之间保持不变。它们都利用了函数是一等对象的事实,这意味着它们可以具有属性。例如:
def f(x):
if not hasattr(f, "i"):
setattr(f, "i", 0)
f.i += x
return f.i
There's also the hack of using a list as a default value for an argument, and then never providing a value for the argument when you call the function:
还有一个技巧是使用列表作为参数的默认值,然后在调用函数时从不为参数提供值:
def f(x, my_list=[0]):
my_list[0] = my_list[0] + x
return my_list[0]
...but I wouldn't recommend using that unless you understand why it works, and maybe not even then.
...但我不建议您使用它,除非您了解它的工作原理,甚至可能不会。
回答by ChipJust
You need to do two things to make your variable global.
您需要做两件事才能使变量成为全局变量。
- Define the variable at the global scope, that is outside the function.
- Use the global statement in the function so that Python knows that this function should use the larger scoped variable.
- 在全局范围内定义变量,即在函数之外。
- 在函数中使用 global 语句,以便 Python 知道该函数应该使用更大的作用域变量。
Example:
例子:
i = 0
def inc_i():
global i
i += 1
回答by Lennart Regebro
A variable not defined in a function or method, but on the module level in Python is as close as you get to a global variable in Python. You access that from another script by
未在函数或方法中定义但在 Python 中的模块级别定义的变量与 Python 中的全局变量一样接近。您可以通过以下方式从另一个脚本访问它
from scriptA import variablename
That will execute the script, and give you access to the variable.
这将执行脚本,并让您访问变量。
回答by Denis Otkidach
The following statement declares i
as global variable:
以下语句声明i
为全局变量:
global i
回答by Paul Du Bois
Your statement "embed in 'main' in order to have the trace function work" is quite ambiguous, but it sounds like what you want is to:
您的声明“嵌入'main'以使跟踪功能正常工作”非常模棱两可,但听起来您想要的是:
- take input from a user
- execute it in some persistent context
- abort execution if it takes too long
- 接受用户的输入
- 在某些持久上下文中执行它
- 如果执行时间过长则中止执行
For this sort of thing, use "exec". An example:
对于这种事情,请使用“exec”。一个例子:
import sys
import time
def timeout(frame,event,arg):
if event == 'line':
elapsed = (time.time()-start) * 1000
code = """
try:
i += 1
except NameError:
i = 1
print 'current i:',i
"""
globals = {}
for ii in range(3):
start = time.time()
sys.settrace(timeout)
exec code in globals
print 'final i:',globals['i']