AttributeError: 'module' 개체에 속성이 없습니다.
Python 모듈이 2개 있습니다.
a.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'
에러의 의미는 무엇입니까?어떻게 고치죠?
상호 최상위 수준 가져오기를 사용하지만, 이는 거의 항상 잘못된 생각입니다.
Python에서 상호 Import가 필요한 경우 함수 내에서 Import하는 방법이 있습니다.
# In b.py:
def cause_a_to_do_something():
import a
a.do_something()
으로 a하게 a.py을 실행할 수 되었습니다.import b
문제를 일으키지 않고.
(어느새 그렇게 수 .)cause_a_to_do_something()
이다. 이치노import
매번 전화를 걸지만 사실 Import 작업은 첫 번째에만 수행됩니다.))))))))))))))))))))))))) 。
, Python은 Python이라는 모듈을 가지고 .commands
Python ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★.로컬 개발 환경에서는 정상적으로 동작했지만 Google App Engine에서 실행할 때 지정된 오류로 인해 추적하기가 어려웠습니다.
이치 a
( 입) )b
★★★★★★★★★★★★★★★★★」b
( 입) )a
이들 중를 먼저은 모듈을 .a
전에b
★★★★★★★★★★★★★★★★★」b.hi()
하지 않습니다.a
.
잘못된 방법으로 Import된 열거형을 참조하면 다음과 같은 오류가 발생합니다.
from package import MyEnumClass
# ...
# in some method:
return MyEnumClass.Member
올바른 Import:
from package.MyEnumClass import MyEnumClass
누군가에게 도움이 되었으면 좋겠다.
저도 같은 문제에 직면했어요.사용으로 고치다reload
.
import the_module_name
from importlib import reload
reload(the_module_name)
gitgit에서 오래된 때 이하였습니다.이 Git을 했습니다..py
되지 않았습니다..pyc
파일입니다..py
및 "파일".pyc
.import
.py
수 ..pyc
files.complete files files files files files files files files.
은 간단히 했습니다..pyc
이치노
모듈이 실제로 Import되지 않았기 때문에 이 오류가 발생하였습니다.코드는 다음과 같습니다.
import a.b, a.c
# ...
something(a.b)
something(a.c)
something(a.d) # My addition, which failed.
이 " " " "가 .AttributeError
인인modmod의 이 인식되지 입니다.a
)a.b
★★★★★★★★★★★★★★★★★」a.c
)은 명시적으로 Import되었으며,import
imported ' Import'a
.
위의 답변들은 모두 훌륭하지만, 저는 여기에 동참하고 싶습니다.위에서 언급한 문제를 발견하지 못한 경우 작업 환경을 정리하십시오.그것은 나에게 효과가 있었다.
ubuntu 18.04(virtualenv, python.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
상세한 것에 대하여는, 여기를 봐 주세요.
순환 Import는 문제를 일으키지만 Python은 이를 완화하는 방법을 가지고 있습니다.
는 " " " " 를 실행하는 입니다.python a.py
은 운행됩니다.a.py
않습니다. 이번에는 ★★★★★★★★★★★★★★★★★★★★★★★.a.py
b -> a -b.-> Imports module b -> Imports module a -> Imports module b.b - Import - Import - no - op - Python 。그리고 b는 현재 빈 모듈입니다. 실행 시b.hi()
,아무것도찾을수없습니다.
에 주의:b.hi()
은 「중」의 기간입니다.a.py
b -> a, b -> "a", "a"a.py
직접적으로.
예에서는 하시면 됩니다.python -c 'import a'
실행인 "" "" " " " " " " " " " " " " 의 첫 입니다.a.py
수입하다
이 에러의 원인은 Import하려고 했던 python 모듈과 같은 이름의 폴더가 있었기 때문입니다.
|-- core <-- empty directory on the same level as the module that throws the error
|-- core.py
그리고 python은 이 폴더를 python 패키지로 취급하여 core.py이 아닌 빈 패키지 "core"에서 가져오려고 했습니다.
어떤 이유에서인지 지점 전환 중에 빈 폴더를 남겨둔 것 같습니다.
그래서 그 폴더를 지웠더니 모든 게 잘 풀렸어요
'b.py'을 저장했습니까? 먼저 'b.py'을 저장해야 합니다.
2개의 프린트를 추가하면, 무슨 일이 일어나고 있는지를 이해할 수 있습니다.
a.py :
print(__name__)
import b
b.py :
print(__name__)
import a
그 후, 다음과 같이 입력합니다.
$ python3 a.py
__main__
b
a
a.py
회회 as as회 as회회 2번으로 하다.__main__
는 그 and and and and and and and and and and and and로 되어 있습니다.a
.
가상 환경에 파일을 쓸 때 파일이 올바른 디렉토리에 저장되지만 파일에 기록된 python이 아직 저장되지 않은 경우가 있습니다.따라서 python이 a.py을 b.py으로 Import할 때 코드는 Import되지 않습니다.다른 용어로 공백입니다.자주 볼 수 있는 오류를 쉽게 식별할 수 있을 것 같습니다.확인해 볼 가치가 있다. - 코디
순환 종속성이 어떻게 나타나는지를 예로 들어 문제와 해결 방법을 알아보겠습니다.파일 window-data-generator.ipynb 메인 실행 파일이 있습니다.여기서 다음 2개의 파일을 Import합니다.
- escape.py
- 돌연변이Types.py
escape.py에 이미 Import된 변환이 있습니다.Types.py 파일 이제 window-data-module.ipynb 파일에서 Mutation 기능을 실행합니다.Types.py은 다음과 같습니다.
import escape as ESC
import MutationTypes
MutationTypes.SINGLE_RES_SUB
는, 「이러다」라고 프롬프트가 표시됩니다.AttributeErrorTraceback (most recent call last) /tmp/ipykernel_4340/4282764781.py in <module> ----> 1 MutationTypes.SINGLE_RES_SUB AttributeError: module 'MutationTypes' has no attribute 'SINGLE_RES_SUB'
어떻게 해결할까요?이미 돌연변이를 가지고 있기 때문에이스케이프 모듈 내에 Import된 파일을 입력합니다.변환 사용이스케이프 모듈을 사용하여 다음과 같이 파일 기능을 입력합니다.
ESC.MutationTypes.SINGLE_RES_SUB
방법은 모르지만, 아래의 변경으로 문제가 해결되었습니다.
파일 이름과 Import 이름은 emoji.py과 같았고 이모티콘을 Import하려고 했습니다.그러나 파일 이름을 바꾸면 문제가 해결되었습니다.
도움이 되었으면 좋겠다
수입 순서가 문제가 된 이유였습니다.
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
리치 힌디의 대답과 비슷하지만, 수업과 함께 보여지는 또 다른 예시입니다.
나는 이 문제를 여러 번 논의했지만 더 깊이 파고들려고 하지 않았다.이제 주요 이슈를 이해했어요.
이번 문제는 다음과 같은 다양한 모듈에서 시리얼라이저(django 및 restframework)를 Import하는 것이었습니다.
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,)
그 때문에, 해결 방법(최상위 레벨의 Import)에 기재되어 있듯이, 다음의 변경을 실시합니다.
# 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
이것이 다른 모든 사람들에게 도움이 되기를 바랍니다.
인사말,
해결된
Python은 a.py 모듈 내의 개체를 찾고 있습니다.
파일 이름을 다른 이름으로 바꾸거나
from __future__ import absolute_import
a.py 모듈의 맨 위에 있습니다.
내 경우 numpy 버전 1.15.0에서 python 2.7로 작업하면
pip install statsmodels=="0.10.0"
언급URL : https://stackoverflow.com/questions/1250103/attributeerror-module-object-has-no-attribute
'programing' 카테고리의 다른 글
SyntaxError: 비ASC함수가 '''을 반환할 때 파일의 II 문자 '\xa3' (0) | 2023.01.15 |
---|---|
업데이트 부분에서 새 값과 이전 값을 모두 사용할 수 있도록 UPSERT를 수행하는 방법 (0) | 2023.01.06 |
중첩 루프 차단 (0) | 2023.01.05 |
비어 있지 않은 폴더를 삭제/삭제하려면 어떻게 해야 합니까? (0) | 2023.01.05 |
PHP CURL OPT_SSL_VERIFYPEER 무시 (0) | 2023.01.05 |