파이썬에서 다른 파일의 함수를 사용하려면 import
를 해야 합니다.
하지만 Java의 reflection처럼 파이썬에서도 import를 하지 않고 동적으로 함수를 호출할 수 있습니다.
import
__import__
는 파이썬의 내장 함수입니다. (특별히 import를 하지 않고 사용할 수 있습니다.)
아래 코드처럼 모듈명(파일명)만 파라미터로 넘겨주면 특정 모듈을 읽어올 수 있습니다.
mod_name = "bbb"
mod = __import__('%s' %(mod_name), fromlist=[mod_name])
print(mod)
bbb모듈을 읽어왔습니다.
<module 'bbb' from '/home/js/testcode/python/bbb.py'>
inspect & getattr
import inspect
를 선언해주면 inspect를 사용할 수 있습니다. inspect는 객체가 갖고 있는 클래스 또는 함수 정보를 알려줍니다.
getattr()
은 inspect로부터 얻은 정보로 클래스 또는 함수 객체를 생성할 수 있습니다.
아래 코드와 결과를 보면 어떻게 사용하는지 알 수 있습니다.
두개의 파일을 생성하고 python aaa.py
로 실행하면 아래 로그와 같은 결과를 얻을 수 있습니다.
참고로 예제는 파이썬 3.5에서 작성하였습니다.
aaa.py
import inspect
from bbb import BBB
# get module from module name
mod_name = "bbb"
mod = __import__('%s' %(mod_name), fromlist=[mod_name])
# get classes from module
class_list = inspect.getmembers(mod, inspect.isclass)
for key, data in class_list:
print('{} : {!r}'.format(key, data))
# get functions from a class
if class_list:
cls_name = class_list[0][0]
cls = getattr(mod, cls_name)
func_list = inspect.getmembers(cls, inspect.isfunction)
for key, data in func_list:
print('{} : {!r}'.format(key, data))
func_name = key
func = getattr(cls, func_name)
func()
bbb.py
class BBB:
def setup():
print("setup!")
def teardown():
print("teardown!")
def testModule1():
print("testModule1!")
def testModule2():
print("testModule2!")
def testModule3():
print("testModule3!")
log
BBB : <class 'bbb.BBB'>
setup : <function BBB.setup at 0x7f111ea54268>
setup!
teardown : <function BBB.teardown at 0x7f111ea542f0>
teardown!
testModule1 : <function BBB.testModule1 at 0x7f111ea54378>
testModule1!
testModule2 : <function BBB.testModule2 at 0x7f111ea54400>
testModule2!
testModule3 : <function BBB.testModule3 at 0x7f111ea54488>
testModule3!
Recommended Posts:
- Python - dict 정렬 (Key, Value로 sorting)
- Python - String을 bytes로 변경하는 방법
- Python - bytes를 String으로 변환하는 방법
- Python - 리스트에서 첫번째, 마지막 요소 가져오는 방법
- Python - 문자열에서 특정 단어 추출
- Python - float을 int로 변경하는 방법
- Python - 특정 문자열로 시작하는 문자열 찾기
- Python - dictionary의 중복 제거 방법
- Python - 리스트가 비어있는지 확인
- Python - 문자열 뒤집기, 문자열 거꾸로 출력
- Python - 현재 날짜, 시간 가져오는 방법
- Python - 두개의 리스트 하나로 합치기
- Python - 리스트 크기(size) 구하기