2016-07-15 69 views
1

我有以下功能,我想連接兩個字符串,我在這裏做什麼錯?在python中獲取名稱錯誤

commands = ["abcd","123"] 

def configure_dev(self, steps): 
    func_name = self.id + ':configure dev' 

    global conf_cmd 
    for key in commands: 
     conf_cmd += key + '\n' 
    print(conf_cmd) 

得到以下錯誤:

conf_cmd + =鍵+ '\ n'

它運行後,我得到這個錯誤: NameError: name 'conf_cmd' is not defined

+3

你在哪裏定義了'conf_cmd'? 'global'不會創建新的變量。 –

+1

你將它設置爲全局但它是未定義的。 – Fallenreaper

+0

謝謝,這真是愚蠢的我。 – Invictus

回答

1

我添加了代碼,解決了您的關鍵問題。

commands = ["abcd","123"] 
def configure_dev(self, steps): 
    func_name = self.id + ':configure dev' 
    global conf_cmd = '' // <-- '' 
    for key in commands: 
    conf_cmd+=key+'\n' 
    print(conf_cmd) 
+0

請記住,每次調用'configure_dev'都會清空字符串。 –

+0

爲真。我不確定他的期望是什麼,但是根據他編碼的期望,每次調用這個函數時,他都打算重新初始化它。或者至少這是我從他們的代碼中挑選出來的。 – Fallenreaper

1

所有你需要做的是要添加: conf_cmd = ''

緊接在commands = ["abcd","123"]

爲什麼? global conf_cmd不創建新字符串,它只是意味着您可以訪問全局變量。