在python中获取nameerror

时间:2016-07-15 18:43:43

标签: python

我有以下功能,我想连接2个字符串,我在这做什么错?

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

2 个答案:

答案 0 :(得分:1)

您需要做的就是添加: conf_cmd = ''

commands = ["abcd","123"]

之后

为什么呢? global conf_cmd不创建新字符串,只是意味着您可以访问全局变量。

答案 1 :(得分: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)