Python:将值从函数传递给函数

时间:2013-03-27 03:21:54

标签: python return

我现在已经和它斗争了三个小时了。

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()

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

Count in main is 1

对于我在其他功能中的用户修改的x和y值,这也是一个问题。虽然我没有在这里修改它们,但我确实包含了它们,因为我需要在代码中稍后在函数之间传递多个值,但是为了示例的缘故,我想将它们放在这里时想要阅读所有这些值。

我的印象是

return [variable]

将变量的CURRENT(即变量在当前函数内的任何变量)传递回其他后续函数。要么我的理解是错的,要么我做错了。

4 个答案:

答案 0 :(得分:2)

你需要这样做:

def firstPass():
    global count

获取要更新的count变量。

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

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

>>> a = 0
>>> def foo():
...   a += 1
...   return a
>>> def bar():
...   global a
...   a += 1
...   return a

使用dis模块拆解这两个函数后,很明显有什么区别:

>>> 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        

答案 1 :(得分:2)

您对return的理解是错误的。

返回的值不仅仅插回到调用者的命名空间中,还必须接收它们。它们也不必同名。

count,a,b = firstPass()

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

答案 2 :(得分:0)

您可能想考虑使用课程。这是维持国家状态的更好容器。

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()

答案 3 :(得分:0)

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

def main():
    count = 0 # initialize it here; you're only running main once
    print "Count in main is",count
    if count == 0:
        count, x, y = firstPass(count) # sets the values from 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()

但是,如果您要在count之外初始化main(),请使用main(count)

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

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

def main (count):
    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(count) # pass it as an argument

但是,如果您只调用main()一次,则可以重写代码和一般结构,如下所示:

def main():
    count = 0
    count, x, y = firstPass(count) # no need to check if it is 0
    # do everything else

def firstPass(count):
    x, y = 5, 2 # multiple assignment, same as x = 5; y = 2
    print "some stuff"
    count += 1 # shorthand for count = count + 1
    print "Count in firstpass is", count
    return count, x, y

main()