Python 修改函数内的全局变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4522786/
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
Modifying a global variable inside a function
提问by Randall J
I have defined the following function:
我定义了以下函数:
def GMM(s1, s2, s3, s4, s5, a):
"""The GMM objective function.
Arguments
---------
si: float
standard deviations of preference distribution
a: float
marginal utility of residutal income
Paramters
---------
Px: array (1,ns)
projector onto nonprice characteristic space
xk, z: arrays (J, 5) and (J, 12)
nonprice char. and instruments
invW: array (12, 12)
GMM weight matrix
Returns
-------
float."""
delta = invert(s1, s2, s3, s4, s5, a, delta0) # Invert market shares to get mean utility
bmean = np.dot(Px, delta) # Project delta onto charancteristic space
xihat = delta - np.dot(xk, bmean) # Compute implied unobservable prod. quality
temp1 = np.dot(xihat.T, z)
if np.any(np.isnan(delta)) == True:
value = 1e+10
else:
value = np.dot(np.dot(temp1, invW), temp1.T)
return np.sqrt(value)
My question pertains to the variable deltabound inside of the function. Outside of the function I will set the initial value of delta0. Now, ultimately I will minimize this function. What I would like to have happen is that each time the function GMMevaluates, deltafrom the previous evaluation is used as the new delta0. I tried defining delta0as a global variable, but it did not seem to work... likely this was my error though. Although, I have read here that generally this is a bad approach. Any suggestions?
我的问题与delta函数内部的变量绑定有关。在函数之外,我将设置 的初始值delta0。现在,我最终会最小化这个函数。我希望发生的是,每次函数GMM求值时,都delta将上一次求值用作新的delta0. 我尝试定义delta0为一个全局变量,但它似乎没有用……虽然这可能是我的错误。虽然,我在这里读到,通常这是一种不好的方法。有什么建议?
回答by pythonFoo
globalVariable = 0
def test():
global globalVariable
globalVariable = 10
test()
print globalVariable
You can edit a global variable in this way.
您可以通过这种方式编辑全局变量。
回答by Laurent Luce
There are multiple ways to achieve what you want. delta is saved across function calls in the following examples.
有多种方法可以实现您想要的。在以下示例中,delta 跨函数调用保存。
1- Class
1-类
class Example:
def __init__(self, value):
self.delta = value
def gmm(self):
self.delta += 1
return self.delta
e = Example(0)
print e.gmm()
2- Generator
2- 发电机
def gmm():
delta = 0
while True:
delta += 1
yield delta
for v in gmm():
print v
3- Function attribute
3- 功能属性
def gmm():
gmm.delta += 1
return delta
gmm.delta = 0
4- Global variable (discouraged as you said):
4-全局变量(如你所说不鼓励):
delta = 0
def gmm():
global delta
delta += 1
return delta
etc...
等等...
回答by richo
When faced with this, a common kludge I use is stuff an object into a module, which then puts it into a namespace accessible by everything in the program. It is a big kludge, but I find it removes any ambiguity about what's global. For standalone stuff I put it into os, if it's an entire project I'll generally create an empty python file called my_globalsand import it, ie
面对这种情况时,我使用的一个常见方法是将对象填充到模块中,然后将其放入程序中所有内容都可以访问的命名空间中。这是一个很大的麻烦,但我发现它消除了关于什么是全局的任何歧义。对于独立的东西,我把它放进去os,如果它是一个完整的项目,我通常会创建一个名为的空 python 文件my_globals并导入它,即
import my_globals
my_globals.thing = "rawp"
def func():
my_globals.thing = "test"
func()
print my_globals.thing # "test"

