다른 모듈에서 함수를 가져 오려고하는데 모듈 이름을 목록에서 찾아야하기 때문에 import 키워드를 사용할 수 없습니다. Python이 지역 네임 스페이스를 검색하지 않습니다.
내가 ExampleFunc를 호출하려고하면
은 일반적으로 내가NameError: global name 'ExampleFunc' is not defined
얻을 수 있지만 명시 적으로 지역 주민에보고 파이썬을 말한다면 그것을 발견한다.
파일 module.py
def ExampleFunc(x):
print x
파일 code.py
def imprt_frm(num,nam,scope):
for key, value in __import__(num,scope).__dict__.items():
if key==nam:
scope[key]=value
def imprt_nam(nam,scope):
imprt_frm("module",nam,scope)
def MainFunc(ary):
imprt_nam("ExampleFunc",locals())
#funtion things
return ExampleFunc(ary) #fails
return locals()["ExampleFunc"](ary) #works
MainFunc("some input")
중복 가능성 [. 지역 주민() 업데이트 (사전) 모든 변수를 추가하지 않습니다 (http://stackoverflow.com/questions/24197720/locals-updatedictionary-doesnt-add-all-the-variables) – bereal