Python 2.7 函数执行期间Python变量未更改
两天前我遇到了一个问题,我找不到一个方法来解决它,它很简单,我的解决方案对我来说似乎“很好”。 以下是我得到的:Python 2.7 函数执行期间Python变量未更改,python-2.7,variables,global,Python 2.7,Variables,Global,两天前我遇到了一个问题,我找不到一个方法来解决它,它很简单,我的解决方案对我来说似乎“很好”。 以下是我得到的: leftKeyCounter = 0 def sendCommand(): # I want to get the counter back to 0. leftKeyCounter = 0 return leftKeyCounter while True: ... leftKeyCounter = leftKeyCounter + 1 使用“sched
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
我寻找的所有解决方案都会将我送回已弃用的“全局变量”,因此我找不到有效的解决方案
感谢您的帮助:)如果您想引用全局范围变量,并修改它们,那么您可以执行以下操作:
leftKeyCounter = 0
def sendCommand():
# I want to get the counter back to 0.
global leftKeyCounter
leftKeyCounter = 0
return leftKeyCounter
while True:
...
leftKeyCounter = leftKeyCounter + 1
这个问题已经得到了回答:如果您想引用全局范围变量,并修改它们,那么您可以执行以下操作:
leftKeyCounter = 0
def sendCommand():
# I want to get the counter back to 0.
global leftKeyCounter
leftKeyCounter = 0
return leftKeyCounter
while True:
...
leftKeyCounter = leftKeyCounter + 1
这个问题已经得到了回答:这是一个范围问题 sendCommand->leftKeyCounter与leftKeyCounter不同-它会告诉您它是0,因为它在函数的范围内
这个堆栈溢出问题有一些很好的答案和关于它是如何工作的信息 这是一个范围界定问题 sendCommand->leftKeyCounter与leftKeyCounter不同-它会告诉您它是0,因为它在函数的范围内
这个堆栈溢出问题有一些很好的答案和关于它是如何工作的信息 之所以这样做,是因为方法内部的
leftKeyCounter
与外部定义的leftKeyCounter
不同,即使它们具有相同的名称
使方法修改外部定义的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)
之所以这样做,是因为方法内部的
leftKeyCounter
与外部定义的leftKeyCounter
不同,即使它们具有相同的名称
使方法修改外部定义的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)
你只需要在
sendCommand()
函数中添加global leftKeyCounter
。你只需要在sendCommand()
函数中添加global leftKeyCounter
。我现在就试试,我已经看到了你提到的这篇文章,但我认为它不受欢迎,我已经在很多地方读过了,这就是为什么我不想使用全局var方法。。。(这篇文章是从2009年开始的,所以…),谢谢,我现在就尝试一下,我已经看到了你提到的这篇文章,但我认为它已经被弃用了,我在很多地方都读过,这就是为什么我不想使用全局变量的方式。。。(这篇文章是从2009年开始的,所以…),谢谢你!会看一看:)谢谢!会看一看:)多谢了,修好了!非常感谢,修正了!