如何在不使用global的情况下将变量传递给下一个函数

时间:2016-04-19 09:15:41

标签: python

我目前正在寻找如何将我保存的变量带入下一个函数。为了说明我的意思,我将在线获取最新的版本号:

try:
     webversion = urllib2.urlopen(
         "http://www." + server + "/version").read().rstrip()
     if webversion > version:
          update_files()
     elif version >= webversion:
          print "[SYSTEM] You have the latest version: v." + version

update_files()函数中,我非常希望将我获得的变量(webversion和可能version)转移到下一个函数。

我正在考虑将此变量设置为全局:

try:
     global webversion
     webversion = urllib2.urlopen(
         "http://www." + server + "/version").read().rstrip()
     if webversion > version:
          update_files()
     elif version >= webversion:
          print "[SYSTEM] You have the latest version: v." + version

这样做有更好的方法/更聪明吗?

2 个答案:

答案 0 :(得分:2)

只需将参数传递给函数:

功能定义:

def update_files(webversion, version):
    # ... function execution

和代码:

try:
     # global webversion we don't need it
     webversion = urllib2.urlopen("http://www." + server + "/version").read().rstrip()
     if webversion > version:
          update_files(webversion, version)
     elif version >= webversion:
          print "[SYSTEM] You have the latest version: v." + version
#And be careful to add except, with try!
except:
    print("Error!")

答案 1 :(得分:1)

以下是将变量从一个函数传递到另一个函数的方法,前提是它们都在同一个文件中:

def my_second_function(my_var):
    print(my_var)


def my_first_function(var_1, var_2):
    my_second_function(var_1):

    # do whatever you want here.
    return True
如果从my_var调用,则

var_1my_first_function具有相同的值:

my_first_function(6,2)

请注意,如果脚本单独运行而不是在其他位置导入,则必须在my_second_function之前定义my_first_function。或者,您可以使用以下命令运行程序:

if __name__ == '__main__': 
    my_second_function(6, 2)

你的案子:

在您的情况下,我们可以将其定义为:

def update_files(web_ver, ver):
    # You can do whatever you want with these, including sending them elsewhere.

    return True  # or whatever


try:
     webversion = urllib2.urlopen("http://www." + server + "/version").read().rstrip()

     if webversion > version:
         update_files(webversion, version)

     else:
         print("[SYSTEM] You have the latest version: v." + version)

 except:
     print("Error!")

 update_files(webversion, version)

您还可以return web_ver, verreturn another_func(web_ver, ver)

相关问题