Python:在函数之间传递值

2024-10-03 17:19:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经和这个战斗了三个小时了。在

ETA-本应提及这一点,但就本类而言,不允许使用全局变量。

在函数main()中,我希望在第一次运行整个函数时运行函数firstPass。firstPass函数初始化一对变量,并打印一些不感兴趣的信息(如果不是第一次看到的话)。在

我正式拥有:

#Initialize variables that need to run before we can do any work here
count = 0

def firstPass():
    x = 5
    y = 2
    print "Some stuff"
    count = count + 1
    print "Count in firstPass is",count
    return count,x,y

def main ():
    print "Count in main is",count
    if count == 0:
        firstPass()
    else:
        #Do a whole bunch of other stuff that is NOT supposed to happen on run #1
        #because the other stuff uses user-modified x and y values, and resetting
        #to start value would just be self-defeating.

main()

这将在第一次传递时正确返回,但在随后的传递中,将返回:

^{pr2}$

这对于我的用户在其他函数中修改的x和y值也是一个问题。虽然我没有在这里修改它们,但我确实包含了它们,因为我需要在以后的代码中在函数之间传递多个值,但是为了这个例子,谁还想看这些呢。。。在

我的印象是

return [variable]

将变量的当前值(即当前函数中的变量)值传递回其他后续函数。不是我的理解错了,就是我做错了。在


Tags: to函数runinreturnthatismain
3条回答

你需要做的是:

def firstPass():
    global count

获取要更新的count变量。在

通过使用global关键字,可以告诉解释器将值加载并存储到全局count变量中,而不是将其保存到同名的局部变量中。例如:

我定义了两个函数,一个使用global

^{pr2}$

在使用^{}模块对这两个函数进行反汇编之后,可以明显看出它们之间的区别:

>>> import dis
>>> dis.dis(foo)
  2           0 LOAD_FAST                0 (a)
              3 LOAD_CONST               1 (1)
              6 INPLACE_ADD         
              7 STORE_FAST               0 (a)

  3          10 LOAD_FAST                0 (a)
             13 RETURN_VALUE        

>>> dis.dis(bar)
  3           0 LOAD_GLOBAL              0 (a)
              3 LOAD_CONST               1 (1)
              6 INPLACE_ADD         
              7 STORE_GLOBAL             0 (a)

  4          10 LOAD_GLOBAL              0 (a)
             13 RETURN_VALUE        

你可能想考虑使用一个类。它是维护状态的更好的容器。在

def firstPass():
    x = 5
    y = 2
    print "Some stuff"
    count = count + 1
    print "Count in firstPass is",count
    return count,x,y        

class MyActivityManager(object):
    def __init__(self):
        """Initialize instance variables"""
        self.run_count = 0

    def run(self):
        if not self.run_count:
            results = firstPass()
            self.run_count += 1
            # consider saving results in the instance for later use
        else:
            # other stuff


if __name__ == "__main__":
    runner = MyActivityManager()
    runner.run()

你对return的理解是错误的。在

返回的值不只是插入回调用者的名称空间,它们必须被接收。他们也不必以相同的名字收到。在

count,a,b = firstPass()

另外,我建议将当前的count作为参数传递到函数中,而不是从全局获取它。这只是更好的风格,使你的功能更容易理解。在

相关问题 更多 >