本文介绍了Python + PyCharm 文件结构问题:AttributeError: 'module' 对象没有属性 'X'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文件结构如下:

  • main.py
  • 加密
    • GetGenerators.py
    • RecHash.py
    • ToInteger.py
    • Utils.py

    GetGenerators.py 看起来像这样:

    GetGenerators.py looks like this:

    import unittest
    import os, sys
    import gmpy2
    from gmpy2 import mpz
    
    sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    from Utils.Utils           import AssertInt, AssertClass
    from Utils.ToInteger       import ToInteger
    from Utils.RecHash         import RecHash    
    
    def GetGenerators(n):
        AssertInt(n)
        assert n >= 0, "n must be greater than or equal 0"
    
        generators = []
    
        # ... irrelevant code...
    
        return generators
    
    
    class GetGeneratorsTest(unittest.TestCase):
        def testGetGenerators(self):
            self.assertEqual(len(GetGenerators(50)), 50)
    
    
    if __name__ == '__main__':
        unittest.main()
    

    当我在 main.py 中使用 GetGenerators 函数时,它工作正常.但是,当我通过右键单击文件在 GetGenerators.py 中运行 Unittests"来运行 GetGenerators.py UnitTests 时,出现以下错误:

    When I'm using the function GetGenerators from inside main.py, it works fine.However, when I'm running the GetGenerators.py UnitTests by rightclicking the file, "Run Unittests in GetGenerators.py", I'm getting the following error:

    文件C:\Program Files (x86)\JetBrains\PyCharm 2016.3.2\helpers\pycharm\nose_helper\util.py",第 70 行,在 resolve_name 中obj = getattr(obj, 部分)

    AttributeError: 'module' 对象没有属性 'GetGenerators'

    AttributeError: 'module' object has no attribute 'GetGenerators'

    我想这与我的文件结构有关,但我没有发现问题.

    I suppose it has something to do with the structure of my files, but I don't see the problem.

    推荐答案

    我以前没有遇到过您的确切问题,但我想我遇到过类似的问题.当我使用 PyCharm 时,我发现如果打开并使用我在 PyCharm 的项目中创建的文件,那么一切正常.我可以导入它们,可以运行它们;没问题.我遇到的问题(与您的类似)是当我打开一个不是在 PyCharm 项目中创建的文件时.我无法导入它们,有时甚至无法正确运行它们.也许只是我愚蠢,或者可能是 PyCharm 的真正错误,但无论如何.可能值得(如果您还没有)在 PyCharm 中创建一个项目并将文件内容复制并粘贴到您在 PyCharm 中创建的文件中.出于某种原因,这在过去对我有用.

    I haven't had your exact problem before, but I think I've had one like it. When I use PyCharm, I find that if open and use files that I've created in a project in PyCharm, then everything works fine. I can import them, can run them; no problems. The problems I run into (which are similar to yours) are when I open a file that was not created within a PyCharm project. I can't import them, and sometimes can't even run them correctly. Maybe it's just me being stupid or maybe a real bug with PyCharm, but whatever the case is. It might be worth (if you haven't already), create a project in PyCharm and copy and paste the file contents into files you create within PyCharm. For some reason, that has worked for me in the past.

    这篇关于Python + PyCharm 文件结构问题:AttributeError: 'module' 对象没有属性 'X'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 19:36