Python 在方法调用后更改变量值

Python 在方法调用后更改变量值,python,Python,假设我有一个方法m1,它有变量x和y。我多次从m1调用方法m2。每次我调用m2,m1,x和y的局部变量的值都需要改变(比如递增/递减)。如何避免方法调用后重复语句 def m2(): #action pass def m1(): x = 0 y = 0 #call to m2 followed by changes in local variable m2() x += 1 y -= 1 #next call to m

假设我有一个方法m1,它有变量x和y。我多次从m1调用方法m2。每次我调用m2,m1,x和y的局部变量的值都需要改变(比如递增/递减)。如何避免方法调用后重复语句

def m2():
    #action
    pass

def m1():
    x = 0
    y = 0

    #call to m2 followed by changes in local variable
    m2()
    x += 1
    y -= 1

    #next call to m2 followed by changes in local variable
    #is there a way to avoid the repetition?
    m2()
    x += 1
    y -= 1

    #...

您可以在
m1
中定义一个函数来为您执行此任务

def m1():
    x = 0
    y = 0

    def _m2():
        m2()
        nonlocal x
        nonlocal y
        x += 1
        y -= 1

    _m2()
    _m2()

    # the value of x and y are 2 and -2 now

我建议您创建一个新的类似包装器的函数:

def call_m2(x,y):
    m2()
    return x+1, y-1
然后将函数调用设置为:

x, y = call_m2(x, y)

如果你知道<>代码> x和<代码> y>代码>是如何改变的(比如,x取1到10的所有值,而y等于<代码> 2x+4 ),然后考虑使用列表。这样做的好处是还可以节省您手动键入对

m2()的所有调用的工作量。


如果
x
y
的值取决于
m2()
的结果,您可以在
while
-循环中执行某种停止条件,并在每次循环迭代结束时更新
x
y
的值,谢谢!这就是我想要的:)我想这在Python3中是有效的。谢谢你的回答。然而,在我的例子中,m2已经返回了一些值。因此,call_m2必须组合所有返回参数。如果可能的话,我想避免这个。谢谢。对我来说,这只是简单的算术。所以也许这会让事情变得复杂一点。
xlist = ['list', 'of', 'all', 'x-values']
ylist = ['list', 'of', 'all', 'y-values']
for x, y in zip(xlist, ylist):
    m2()