2017-02-08 502 views
0

我是新來的Python,我非常瞭解其他人的代碼並將它合併到我的代碼中,所以我爲這個醜陋道歉。返回函數,真混淆

我有這個變量random_collector = ''。隨着代碼的繼續,我將random_collector設置爲非空白字符串。最後,我爲random_collector設置了返回功能。問題是:會返回一個空白字符串還是一個非空白字符串

def add_csv(): 
    random_collector = '' 
    sitevalue = '' 
    path = raw_input('path to csv file: ') 
    with open(path, 'r') as ifile: 
     reader = csv.reader(ifile) 
     reader.next() 
     for row in reader: 
      deviceip = row[1] 
      displayname = row[0] 
      snmpc = row[2] 
      alert_priority = row[3] 
      monitoring_templates = row[4] 
      pd_alert_service = row[5] 
      site_code = row[6] 
      team_owner = row[7] 
      if displayname_pattern.match(displayname): 
       cut_displayname = displayname[0:4] 
       print cut_displayname 
       if cut_displayname in site: 
        sitevalue = site.get(cut_displayname) 
        cut_office = cut_displayname[0:3] 
        if cut_office in na_office: 
         random_collector = random.choice(na_collector) 
         lm_add_api(deviceip, displayname, random_collector, sitevalue, snmpc, alert_priority, monitoring_templates, pd_alert_service, site_code, team_owner) 
         time.sleep(5) 
        elif cut_office in apac_office: 
         random_collector = random.choice(apac_office) 
         lm_add_api(deviceip, displayname, random_collector, sitevalue, snmpc, alert_priority, monitoring_templates, pd_alert_service, site_code, team_owner) 
        elif cut_office in emea_office: 
         random_collector = random.choice(emea_office) 
         lm_add_api(deviceip, displayname, random_collector, sitevalue, snmpc) 
       else: 
        print 'Site format is not a recongnized' 
        time.sleep(2) 
        add() 
      else: 
       print 'Double check the site code, device group not found in Logic Monitor' 
       time.sleep(2) 
       add() 

    return deviceip, displayname, random_collector, sitevalue, snmpc, alert_priority, monitoring_templates, pd_alert_service, site_code, team_owner 

我的困惑在這個代碼塊中的第二部分是我打電話叫lm_add_api(deviceip, displayname, random_collector, sitevalue, snmpc, alert_priority, monitoring_templates, pd_alert_service, site_code, team_owner)另一個功能,它採取的變量random_collector。它是從random_collector = random.choice(na_collector)得到的回報變量還是結果?

if cut_office in na_office: 
         random_collector = random.choice(na_collector) 
         lm_add_api(deviceip, displayname, random_collector, sitevalue, snmpc, alert_priority, monitoring_templates, pd_alert_service, site_code, team_owner) 
+5

如果你想知道它返回的是什麼,爲什麼不運行它並看看? –

回答

1

返回的random_collector的值將是返回時存儲在該變量中的任何值。如果代碼獲取並執行將值賦給random_collector的代碼行中的一行,那將是返回的值。如果沒有,它會保持你給它的初始值(空字符串)。

對於第二個問題,您使用從random.choice(na_collector)得到的值調用lm_add_api。

需要注意的是,Python與其他命令式編程語言一樣,在代碼執行時更改狀態並保持更新的狀態值。所以無論何時你改變一個變量的值,它都會保持這個更新的值。代碼如:

x = 1 
x = 2 
x = 3 
x = 4 
print x 

只會打印'4'。所有這些先前的任務都被覆蓋。