2017-12-11 4 views
0

다른 파이썬 파일에서 변수를 가져 오려고합니다.다른 파일에서 변수 가져 오기 (importlib)?

a.py이 - 작품,하지만 난 정적 이름 a

from a import * 
print(text) 

c.py 수 없습니다 - -

text="Hello, world" 
print("imported") 

b.py를 가져올 수

import importlib 

X = "a" 

try: 
    text = "" 
    i = importlib.import_module(X) 
    print(i) 
    print(text) 
except ImportError as err: 
    print('Error:', err) 

try: 
    text = "" 
    i = importlib.__import__(X , globals=True, locals=True, fromlist=[], level=0) 
    print(i) 
    print(text) 
except ImportError as err: 
    print('Error:', err) 

try: 
    text = "" 
    i = importlib.__import__(X , globals=True, locals=True, fromlist=[text], level=0) 
    print(i) 
    print(text) 
except ImportError as err: 
    print('Error:', err) 

ouptut 작동하지 것은 :

imported 
<module 'a' from '/tmp/a.py'> 

<module 'a' from '/tmp/a.py'> 

<module 'a' from '/tmp/a.py'> 

그러나 text은 작동하지 않습니다.

d.py -

X = "a" 
from X import * 
print(text) 

작동하지는 from MODULE import *importlib를 사용할 수 있습니까?

+0

실제로 별표 가져 오기를 사용해서는 안됩니다. 별 가져 오기는 네임 스페이스를 오염시키고, 코드를 유지 관리 할 수 ​​없으며 (이름을 가져온 모듈을 알지 못합니다.) 예기치 않은 방식으로 중단됩니다. 이전에 가져온 다른 이름을 음영 처리하는 가져온 모듈의 새 이름으로 정의). –

답변

1

별 수입 ("XXX 가져 오기 *에서")입니다 나쁜 연습 (그리고 pep08에 적극적으로 낙담 한) 빠른 검사/실험/디버깅을위한 파이썬 쉘의 편리한 바로 가기로만 사용해야합니다.

그래서 b.py 코드는 a 모듈을 수입하고 완전한 경로 즉 사용해야 중 하나를 명시 적으로 a에서 원하는 이름 (들)을 가져 (최악의)

# b.py 
import a 
print(a.text) 

또는 :

# b.py 
from a import text 
print(text) 

이 두 번째 해법은 예상되는 fior 가변 전역처럼 작동하지 않을 것입니다.이 경우 textb에 모듈 로컬 이름이되므로 a.text이 리바운드되면 (재 할당 d) 어딘가에서 b.text은 영향을받지 않습니다. 그러나 가변 전역이 이제 RightThing을하고 첫 번째 솔루션 (모듈 가져 오기 + 완전한 경로)를 선택 가정

... 어쨌든 악, importlib을 사용하여 "번역"는 다음과 같습니다

import importlib 
module_name = "a" 
module = importlib.import_module(module_name) 
print(module.text) 

FWIW importlib.__import__()을 사용하려는 모든 시도가 잘못되었습니다. globalsdict이고, fromlist은 이름 (문자열) 목록입니다. 그러나 실제로 importlib.import_module 대신 importlib.__import__()을 사용하는 데는 그다지 좋은 이유가 없습니다.

-2

OOP (Object Orientated Programming)를보고 싶을 것 같은데요. 먼저 클래스를 초기화하고 싶습니다. 다음으로는 해당 클래스에 대한 변수를 작성해야합니다. 세 번째는 다른 모듈에 해당 클래스의 인스턴스를 호출 할

# 1 초기화 클래스

클래스 testHello (객체) :

#2. initialise variables 
    def __init__(self): 
     self.text = "hello world" 

    #3. instantiate the class 

from <name of python class without py> import * 

classInstance = testHello() 

#4. print desired variable 
print(classInstance.text) 
+0

이것은 OP 질문에 대한 답변이 아니며 OP가 요청하는 항목에는 추가 수업이 필요하지 않습니다. –

관련 문제