Python变量在函数期间未更改

时间:2016-03-24 10:12:27

标签: python-2.7 variables global

我2天前碰到了一个问题,我找不到办法让它发挥作用,这很简单,我的解决方案对我来说似乎“好”。 这是我得到的:

leftKeyCounter = 0

def sendCommand():
    # I want to get the counter back to 0.
    leftKeyCounter = 0
    return leftKeyCounter

while True:
...
leftKeyCounter = leftKeyCounter + 1

使用“schedule”帮助程序每5秒自动调用sendCommand()函数。 例如,在我的终端中,“leftKeyCounter”没有改变;如果它是4,当函数运行时,它告诉我变量现在是0,但如果我再添加一个,它就是5 ......

我寻找的所有解决方案都会将我发回给已被弃用的“全局变量”,因此我找不到有效的解决方案......

感谢您的帮助:)

3 个答案:

答案 0 :(得分:4)

这样做的原因是因为您的方法中的leftKeyCounter与外部定义的lefKeyCounter不同 - 即使它们具有相同的名称。

使方法修改外部定义的leftKeyCounter的一种方法是使用global关键字 - 因此它知道它正在修改全局版本变量。

另一种方法是传入变量,并返回修改后的值,然后保存此返回值:

def sendCommand(leftKeyCounter):
   # do something here
   if something_is_true:
       leftKeyCounter = 0
   return leftKeyCounter # this is the new value of leftKeyCounter

leftKeyCounter = 0 # this is the starting value
while True:
   # do something here
   leftKeyCounter = sendCommand(leftKeyCounter)

答案 1 :(得分:2)

如果您想引用全局范围变量,并修改它们,那么您可以执行以下操作:

leftKeyCounter = 0

def sendCommand():
    # I want to get the counter back to 0.
    global leftKeyCounter
    leftKeyCounter = 0
    return leftKeyCounter

while True:
...
leftKeyCounter = leftKeyCounter + 1

这个问题已经回答:Using global variables in a function other than the one that created them

答案 2 :(得分:2)

这是一个范围问题。

sendCommand - > leftKeyCounter与leftKeyCounter不同 - 它会告诉你它为0,因为它在函数范围内。

这个堆栈溢出问题有一些很好的答案和有关其工作原理的信息。 Short Description of the Scoping Rules?