2016-07-15 70 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不创建新字符串,它只是意味着您可以访问全局变量。