1

我已经为此奋斗了三个小时。

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

4 回答 4

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        
于 2013-03-27T03:24:48.750 回答
2

你的理解return是错误的。

返回的值不仅被插入回调用者的命名空间,还必须被接收。他们也不必以相同的名字接收。

count,a,b = firstPass()

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

于 2013-03-27T03:41:18.597 回答
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()
于 2013-03-27T03:29:22.320 回答
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()
于 2013-03-27T17:37:53.323 回答