반응형

[파이썬 기초] 다른 폴더 파일 import 하는 방법

main.py 파일과 다른 경로에 있는 class를 import하는 방법에 대해 소개합니다.

프로그램이 복잡하고 길어질수록 접근성 향상을 위해 기능별로 묶어 관리하는 것이 유지보수에 적합합니다.
다른 폴더에 정리한 내용을 import 하는 방법에 대해서 소개합니다.




목차:




1. __init__.py 파일 생성

_otherModules 폴더에서 init_class.py를 불러옵니다.

  • 불러오고자 하는 폴더( _otherModules )에 __init__.py 파일을 생성합니다.

  • 예시 _otherModules 폴더에 __init__.py 생성

  • 불러오고자 하는 class의 스크립트

      # init_class.py
      class showMessage:
          def msg(self):
              print("showMessage Class를 불러왔습니다.")
  • 위의 showMessage Class를 불러오기 위해 아래와 같이 __init__.py를 작성합니다.

      # __init__.py
      from . init_class import showMessage



2. main 스크립트에서 불러오기

_otherModules 폴더에서 init_class.py를 불러옵니다.

  • 메인 스크립트에서 _otherModules 폴더의 모든 내용을 import 하고 class showMessage를 불러옵니다.
      #main.py
      from _otherModules import showMessage
      test = showMessage()
      test.msg()


python3.9 | camp-lee@naver.com

반응형

+ Recent posts