【问题标题】:Why am I getting a "NameError: name 'database' is not defined", even if I am defining main?为什么我得到“NameError:名称'数据库'未定义”,即使我正在定义主?
【发布时间】:2020-06-27 22:26:14
【问题描述】:

当我尝试运行我的代码时,出现名称错误:

Traceback (most recent call last):
  File "dna.py", line 24, in <module>
    main ()
  File "dna.py", line 15, in main
    STR_searcher()
  File "dna.py", line 19, in STR_searcher
    STR_dict = dict.fromkeys(range(1, len(database.fieldnames)))
NameError: name 'database' is not defined

当我将辅助函数放在顶部时,程序可以运行,但我计划使用更多函数,因此我想将它们放在底部并将第一个定义为 main。我也尝试过使用if __name__ == "__main__": main(),但这也没有用。那么如何在确保定义所有内容的同时将其他函数放在 main 之下?

from sys import argv, exit
import csv
from collections import OrderedDict

def main():
    if len(argv) != 3:
        print("Usage: python dna.py data.csv sequence.txt")
        exit(1)
    
with open(argv[1]) as csv_file: 
    database = csv.DictReader(csv_file)

    with open(argv[2]) as txt_file: 
        sequence = txt_file.read()
        STR_searcher()
                    
        
def STR_searcher():
    STR_dict = dict.fromkeys(range(1, len(database.fieldnames)))
    for i in range(len(STR_dict)):
        for j in range(len(sequence)):
            print("hello")        
            
main ()

【问题讨论】:

  • 我想我不明白为什么您希望在main 中创建的database 值可以在STR_searcher 中使用。您是否还期望 csv_filetxt_file 在那里可用?
  • “那么我怎样才能将我的其他函数放在 main 之下,同时确保所有内容都已定义?”看来您认为问题是由在STR_searcher 之前定义main() 引起的?这是不正确的。
  • @KarlKnechtel 我在 3 周前开始编码,并在 3 天前开始使用 python,所以说实话我总体上很困惑。我之前使用过 C,所以我习惯于在使用变量之前定义我的变量,并且当 STR_searcher 函数高于程序的其余部分时,我的程序工作,所以这就是为什么这对我来说是个问题。
  • 无论您将函数放入的顺序如何,您尝试执行的操作在 C 中也不起作用。我认为您可能还误解了“定义变量”在 C 中的工作方式。一般这里需要理解的概念是变量范围

标签: python nameerror traceback


【解决方案1】:

这是因为在STR_searcher()的函数范围内没有定义变量database。要将变量赋予函数,将其定义为: def STR_searcher(database): 并从 main 函数中调用它,例如 STR_searcher(database)

【讨论】:

    【解决方案2】:

    发生这种情况是因为您的 database 变量是在您的 main 函数的上下文中定义的,而在 STR_searcher 内部它就好像它不存在一样。考虑将其移至一个类,例如:

    def MyClass(object):
        def __init__(self):
            self.database =None
            self.sequence=None
        
        def main(self):
            if len(argv) != 3:
                print("Usage: python dna.py data.csv sequence.txt")
                exit(1)
                
            with open(argv[1]) as csv_file: 
                self.database = csv.DictReader(csv_file)
            
                with open(argv[2]) as txt_file: 
                    self.sequence = txt_file.read()
                    self.STR_searcher()
                            
                
        def STR_searcher(self):
            STR_dict = dict.fromkeys(range(1, len(self.database.fieldnames)))
            for i in range(len(STR_dict)):
                for j in range(len(self.sequence)):
                    print("hello")    
    

    然后您可以通过以下方式运行它:

    Myclass().main()
    

    【讨论】:

      【解决方案3】:

      你应该将变量传递给函数

      from collections import OrderedDict
      from sys import argv, exit
      import csv
      
      def main():
          if len(argv) != 3:
              print("Usage: python dna.py data.csv sequence.txt")
              exit(1)
      
          with open(argv[1]) as csv_file: 
              database = csv.DictReader(csv_file)
      
          with open(argv[2]) as txt_file: 
              sequence = txt_file.read()
          
          STR_searcher(database, sequence)
              
      def STR_searcher(database, sequence):
          STR_dict = dict.fromkeys(range(1, len(database.fieldnames)))
          for i in range(len(STR_dict)):
              for j in range(len(sequence)):
                  print("hello")        
                  
      if __name__ == "__main__":
          main()
      

      或者您可以使用 global 关键字,但这不是一个好方法。

      from collections import OrderedDict
      from sys import argv, exit
      import csv
      
      database = None
      sequence = None
      
      def main():
          global database
          global sequence
      
          if len(argv) != 3:
              print("Usage: python dna.py data.csv sequence.txt")
              exit(1)
      
          with open(argv[1]) as csv_file: 
              database = csv.DictReader(csv_file)
      
          with open(argv[2]) as txt_file: 
              sequence = txt_file.read()
          
          STR_searcher()
                 
      def STR_searcher():
          global database
          global sequence
          
          STR_dict = dict.fromkeys(range(1, len(database.fieldnames)))
          for i in range(len(STR_dict)):
              for j in range(len(sequence)):
                  print("hello")        
                  
      if __name__ == "__main__":
          main()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-15
        • 2021-12-20
        • 2010-12-20
        • 2021-12-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多