AttributeError:“模块”对象没有属性

问题:AttributeError:“模块”对象没有属性

我有两个python模块:

py

import b

def hello():
  print "hello"

print "a.py"
print hello()
print b.hi()

b.py

import a

def hi():
  print "hi"

当我跑步时a.py,我得到:

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

错误是什么意思?我如何解决它?

I have two python modules:

a.py

import b

def hello():
  print "hello"

print "a.py"
print hello()
print b.hi()

b.py

import a

def hi():
  print "hi"

When I run a.py, I get:

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

What does the error mean? How do I fix it?


回答 0

您有相互的顶级导入,这几乎总是一个坏主意。

如果您确实必须在Python中进行相互导入,则可以通过在函数中导入它们来实现:

# In b.py:
def cause_a_to_do_something():
    import a
    a.do_something()

现在,a.py可以安全地进行操作import b而不会引起问题。

(乍看之下,cause_a_to_do_something()效率似乎很低,因为import每次调用它都会这样做,但是实际上导入工作只是第一次完成。第二次及以后的导入模块是一种快速的操作。 )

You have mutual top-level imports, which is almost always a bad idea.

If you really must have mutual imports in Python, the way to do it is to import them within a function:

# In b.py:
def cause_a_to_do_something():
    import a
    a.do_something()

Now a.py can safely do import b without causing problems.

(At first glance it might appear that cause_a_to_do_something() would be hugely inefficient because it does an import every time you call it, but in fact the import work only gets done the first time. The second and subsequent times you import a module, it’s a quick operation.)


回答 1

在不经意地将模块命名为与标准Python模块之一相同的模块时,我也看到了此错误。例如,我有一个名为的模块commands,它也是一个Python库模块。由于它无法在我的本地开发环境中正常运行,因此很难追踪,但是在Google App Engine上运行时由于指定的错误而失败。

I have also seen this error when inadvertently naming a module with the same name as one of the standard Python modules. E.g. I had a module called commands which is also a Python library module. This proved to be difficult to track down as it worked correctly on my local development environment but failed with the specified error when running on Google App Engine.


回答 2

问题在于模块之间的循环依赖关系。a进口bb进口a。但是其中一个需要首先被加载-在这种情况下,python最终在初始化模块a之前结束了bb.hi()当您尝试在python 中访问它时它尚不存在a

The problem is the circular dependency between the modules. a imports b and b imports a. But one of them needs to be loaded first – in this case python ends up initializing module a before b and b.hi() doesn’t exist yet when you try to access it in a.


回答 3

我通过引用以错误方式导入的枚举而收到此错误,例如:

from package import MyEnumClass
# ...
# in some method:
return MyEnumClass.Member

正确导入:

from package.MyEnumClass import MyEnumClass

希望对某人有帮助

I got this error by referencing an enum which was imported in a wrong way, e.g.:

from package import MyEnumClass
# ...
# in some method:
return MyEnumClass.Member

Correct import:

from package.MyEnumClass import MyEnumClass

Hope that helps someone


回答 4

我遇到了此错误,因为实际上未导入模块。代码如下:

import a.b, a.c

# ...

something(a.b)
something(a.c)
something(a.d)  # My addition, which failed.

最后一行导致AttributeError。原因是我没有注意到aa.ba.c)的子模块已显式导入,并假定该import语句实际上是导入的a

I experienced this error because the module was not actually imported. The code looked like this:

import a.b, a.c

# ...

something(a.b)
something(a.c)
something(a.d)  # My addition, which failed.

The last line resulted in an AttributeError. The cause was that I had failed to notice that the submodules of a (a.b and a.c) were explicitly imported, and assumed that the import statement actually imported a.


回答 5

我遇到了同样的问题。使用修复reload

import the_module_name
from importlib import reload
reload(the_module_name)

I faced the same issue. fixed by using reload.

import the_module_name
from importlib import reload
reload(the_module_name)

回答 6

当我从git中检出较旧版本的存储库时遇到了这个问题。Git替换了我的.py文件,但保留了未跟踪的.pyc文件。由于.py文件和.pyc文件不同步,因此文件中的import命令.py无法在文件中找到相应的模块.pyc

解决方案就是删除.pyc文件,然后让它们自动重新生成。

I ran into this problem when I checked out an older version of a repository from git. Git replaced my .py files, but left the untracked .pyc files. Since the .py files and .pyc files were out of sync, the import command in a .py file could not find the corresponding module in the .pyc files.

The solution was simply to delete the .pyc files, and let them be automatically regenerated.


回答 7

ubuntu 18.04virtualenvpython.3.6.x)上,以下重新加载代码段为我解决了该问题:

main.py

import my_module  # my_module.py
from importlib import reload # reload 
reload(my_module)

print(my_module)
print(my_modeule.hello())

哪里:

|--main.py    
|--my_module.py

有关更多文档,请检查:这里

on ubuntu 18.04 ( virtualenv, python.3.6.x), the following reload snippet solved the problem for me:

main.py

import my_module  # my_module.py
from importlib import reload # reload 
reload(my_module)

print(my_module)
print(my_modeule.hello())

where:

|--main.py    
|--my_module.py

for more documentation check : here


回答 8

以上所有答案都很不错,但我想在此鸣叫。如果没有发现上述任何问题,请尝试清理您的工作环境。它为我工作。

All the above answers are great, but I’d like to chime in here. If you did not spot any issue mentioned above, try clear up your working environment. It worked for me.


回答 9

不知道如何,但是以下更改对我的问题进行了排序:

我的文件名和导入名称相同,例如,我的文件名为emoji.py,并且我尝试导入emoji。但是更改文件名解决了这个问题。

希望有帮助

Not sure how but the below change sorted my issue:

i was having the name of file and import name same for eg i had file name as emoji.py and i was trying to import emoji. But changing the name of file solved the issue .

Hope so it helps


回答 10

循环导入会引起问题,但是Python可以缓解这种问题。

问题是当您运行时python a.py,它会运行a.py但不会将其标记为模块导入。因此依次a.py->导入模块b->导入模块a->导入模块b。自从b导入以来,最后一次导入a-no操作,Python对此进行了防范。b现在是一个空模块。因此,当它执行时b.hi(),它什么也找不到。

请注意,b.hi()执行的是在a.py->模块b->模块a 期间执行的,而不是a.py直接执行。

在您的特定示例中,您只能python -c 'import a'在顶层运行,因此的第一次执行a.py被注册为导入模块。

Circular imports cause problems, but Python has ways to mitigate it built-in.

The problem is when you run python a.py, it runs a.py but not mark it imported as a module. So in turn a.py -> imports module b -> imports module a -> imports module b. The last import a no-op since b is currently being imported and Python guards against that. And b is an empty module for now. So when it executes b.hi(), it can’t find anything.

Note that the b.hi() that got executed is during a.py -> module b -> module a, not in a.py directly.

In your specific example, you can just run python -c 'import a' at top-level, so the first execution of a.py is registered as importing a module.


回答 11

订单进口的就是为什么我有问题的原因:

a.py

############
# this is a problem
# move this to below
#############
from b import NewThing

class ProblemThing(object):
    pass

class A(object):
   ###############
   # add it here
   # from b import NewThing
   ###############
   nt = NewThing()
   pass

b.py

from a import ProblemThing

class NewThing(ProblemThing):
    pass

只是它的外观的另一个示例,类似于RichieHindie的答案,但带有类。

The order of the importing was the reason why I was having issues:

a.py:

############
# this is a problem
# move this to below
#############
from b import NewThing

class ProblemThing(object):
    pass

class A(object):
   ###############
   # add it here
   # from b import NewThing
   ###############
   nt = NewThing()
   pass

b.py:

from a import ProblemThing

class NewThing(ProblemThing):
    pass

Just another example of how it might look, similar to RichieHindie’s answer, but with classes.


回答 12

我已经多次遇到这个问题,但是我并没有尝试更深入地研究它。现在我了解了主要问题。

这次我的问题是从不同的模块(例如以下)中导入序列化器(django和restframework):

from rest_framework import serializers

from common import serializers as srlz
from prices import models as mdlpri

# the line below was the problem 'srlzprod'
from products import serializers as srlzprod

我遇到这样的问题:

from product import serializers as srlzprod
ModuleNotFoundError: No module named 'product'

我要完成的工作如下:

class CampaignsProductsSerializers(srlz.DynamicFieldsModelSerializer):
    bank_name = serializers.CharField(trim_whitespace=True,)
    coupon_type = serializers.SerializerMethodField()
    promotion_description = serializers.SerializerMethodField()

    # the nested relation of the line below
    product = srlzprod.ProductsSerializers(fields=['id','name',],read_only=True,)

因此,正如上面几行提到的解决方法(顶级导入)所述,我继续进行以下更改:

# change
product = srlzprod.ProductsSerializers(fields=['id','name',],read_only=True,)
# by 
product = serializers.SerializerMethodField()

# and create the following method and call from there the required serializer class
def get_product(self, obj):
        from products import serializers as srlzprod
        p_fields = ['id', 'name', ]
        return srlzprod.ProductsSerializers(
            obj.product, fields=p_fields, many=False,
        ).data

因此,django runserver的执行没有问题:

./project/settings/manage.py runserver 0:8002 --settings=settings_development_mlazo
Performing system checks...

System check identified no issues (0 silenced).
April 25, 2020 - 13:31:56
Django version 2.0.7, using settings 'settings_development_mlazo'
Starting development server at http://0:8002/
Quit the server with CONTROL-C.

代码行的最终状态如下:

from rest_framework import serializers

from common import serializers as srlz
from prices import models as mdlpri

class CampaignsProductsSerializers(srlz.DynamicFieldsModelSerializer):
    bank_name = serializers.CharField(trim_whitespace=True,)
    coupon_type = serializers.SerializerMethodField()
    promotion_description = serializers.SerializerMethodField()
    product = serializers.SerializerMethodField()

    class Meta:
        model = mdlpri.CampaignsProducts
        fields = '__all__'

    def get_product(self, obj):
        from products import serializers as srlzprod
        p_fields = ['id', 'name', ]
        return srlzprod.ProductsSerializers(
            obj.product, fields=p_fields, many=False,
        ).data

希望这对其他人有帮助。

问候,

I have crossed with this issue many times, but I didnt try to dig deeper about it. Now I understand the main issue.

This time my problem was importing Serializers ( django and restframework ) from different modules such as the following :

from rest_framework import serializers

from common import serializers as srlz
from prices import models as mdlpri

# the line below was the problem 'srlzprod'
from products import serializers as srlzprod

I was getting a problem like this :

from product import serializers as srlzprod
ModuleNotFoundError: No module named 'product'

What I wanted to accomplished was the following :

class CampaignsProductsSerializers(srlz.DynamicFieldsModelSerializer):
    bank_name = serializers.CharField(trim_whitespace=True,)
    coupon_type = serializers.SerializerMethodField()
    promotion_description = serializers.SerializerMethodField()

    # the nested relation of the line below
    product = srlzprod.ProductsSerializers(fields=['id','name',],read_only=True,)

So, as mentioned by the lines above how to solve it ( top-level import ), I proceed to do the following changes :

# change
product = srlzprod.ProductsSerializers(fields=['id','name',],read_only=True,)
# by 
product = serializers.SerializerMethodField()

# and create the following method and call from there the required serializer class
def get_product(self, obj):
        from products import serializers as srlzprod
        p_fields = ['id', 'name', ]
        return srlzprod.ProductsSerializers(
            obj.product, fields=p_fields, many=False,
        ).data

Therefore, django runserver was executed without problems :

./project/settings/manage.py runserver 0:8002 --settings=settings_development_mlazo
Performing system checks...

System check identified no issues (0 silenced).
April 25, 2020 - 13:31:56
Django version 2.0.7, using settings 'settings_development_mlazo'
Starting development server at http://0:8002/
Quit the server with CONTROL-C.

Final state of the code lines was the following :

from rest_framework import serializers

from common import serializers as srlz
from prices import models as mdlpri

class CampaignsProductsSerializers(srlz.DynamicFieldsModelSerializer):
    bank_name = serializers.CharField(trim_whitespace=True,)
    coupon_type = serializers.SerializerMethodField()
    promotion_description = serializers.SerializerMethodField()
    product = serializers.SerializerMethodField()

    class Meta:
        model = mdlpri.CampaignsProducts
        fields = '__all__'

    def get_product(self, obj):
        from products import serializers as srlzprod
        p_fields = ['id', 'name', ]
        return srlzprod.ProductsSerializers(
            obj.product, fields=p_fields, many=False,
        ).data

Hope this could be helpful for everybody else.

Greetings,


回答 13

就我而言,使用numpy版本1.15.0的python 2.7时,它与

pip install statsmodels=="0.10.0"

In my case working with python 2.7 with numpy version 1.15.0, it worked with

pip install statsmodels=="0.10.0"