简体   繁体   English

如何修复导入文件中的属性错误?

[英]How to fix Attribute Error in importing files?

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\Main\Programming\Python\Console\mod_project\auto_message_mod.py", line 5, in <module>
    import mod
  File "D:\Main\Programming\Python\Console\mod_project\mod.py", line 77, in <module>
    main()
  File "D:\Main\Programming\Python\Console\mod_project\mod.py", line 18, in main
    main_program_menu()
  File "D:\Main\Programming\Python\Console\mod_project\mod.py", line 36, in main_program_menu
    auto.auto_message_tools()
AttributeError: partially initialized module 'auto_message_mod' has no attribute 'auto_message_tools' (most likely due to a circular import)

I keep getting these errors while I try to import the file call auto_message_mod.py into mod.py and in mod.py , I tried to call the function auto_message_tools (these files are in the same folder).当我尝试将文件调用auto_message_mod.py导入mod.pymod.py时,我不断收到这些错误,我尝试调用 function auto_message_tools (这些文件位于同一文件夹中)。 I also have imported the other files into mod.py and it worked perfectly.我还将其他文件导入mod.py并且效果很好。 Except auto_message_mod.py .除了auto_message_mod.py I have written import auto_message_mod as auto but it was not working.我已将import auto_message_mod as auto但它不起作用。 I have already tried auto.auto_message_tools() but didn't work.我已经尝试过auto.auto_message_tools()但没有用。 Can someone please help me?有人可以帮帮我吗?

Python is a scripting language, which is interpreted line by line. Python是一种脚本语言,逐行解释。 An import statement literally means that it will jump into that file and start reading over it, before jumping back to the original file and continuing to read through that. import语句的字面意思是它将跳转到该文件并开始阅读它,然后再跳转回原始文件并继续阅读该文件。 Read more here . 在这里阅读更多。

You can see that in your traceback, you import a file, which then calls a function that is presumably in the original.您可以看到,在您的回溯中,您导入了一个文件,然后该文件调用了可能是原始文件中的 function。

The best way to fix this is to separate import-time code from run-time code.解决此问题的最佳方法是将导入时代码与运行时代码分开。 That means everything should import before the code is run, meaning all your code outside your main file should be only found within functions and classes.这意味着所有内容都应该在代码运行之前导入,这意味着主文件之外的所有代码都应该只能在函数和类中找到。 That means that you are much less likely to create a circular import like this, since all the code will already be initialised before you call any of it.这意味着您不太可能像这样创建循环导入,因为所有代码在您调用任何代码之前都已经初始化。

If that doesn't work, experimenting with moving culprit import statements to the bottom often helps, although it is stylistically bad, so I'd only use it as a last resort.如果这不起作用,尝试将罪魁祸首导入语句移到底部通常会有所帮助,尽管它在风格上很糟糕,所以我只会将它用作最后的手段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM