[나도코딩 파이썬 기본편] #11 모듈, 패키지 따라하기

2022. 2. 3. 04:07독학으로 취업 문 뿌수기/Python

728x90
반응형
SMALL

1. 모듈

<theater_module.py>
#정가
def price(people):
    print("{}명 가격은 {}원 입니다." .format(people, people * 10000))
#조조할인
def price_morning(people):
    print("{}명 조조 할인 가격은 {}원 입니다." .format(people, people * 6000))
#군인할인
def price_soldier(people):
    print("{}명 군인 할인 가격은 {}원 입니다." .format(people, people * 4000))
 
import theater_module
theater_module.price(3)
theater_module.price_morning(4)
theater_module.price_soldier(2)
 
<위와 같은 출력 값>
from theater_module import>>> 또는 price만 출력하고자 하면 *대신 price를 적으면 된다.
price(3)
price_morning(4)
price_soldier(2)
 
  • module.py 파일은 새로 만들어서 불러오고자 하는 파일 내에 import module을 해준다.
  • 모듈 이름이 길 경우 as를 이용하여 'import theater_modile as mv'형태로 별명을 지어줄 수 있다.
from theater_module import price_morning as price
price(4>>> 정가의 price 함수가 아닌 price_morning을 의미한다

2. 패키지

import travel.thailand 
trip_to = travel.thailand.ThailandPackage()
trip_to.detail()
from travel import thailand
trip_to = thailand.ThailandPackage()
trip_to.detail()
from travel.thailand import ThailandPackage
trip_to = ThailandPackage()
trip_to.detail()
  • import 폴더명.파일명 순
  • 위의 3개의 식 모두 동일한 출력값을 가진다. 형태만 다름.

class ThailandPackage:
    def detail(self):
        print("[태국 패키지 3박 5일] 방콕, 파타야 여행 50만원")
  • travel 폴더 내 thailand, vietnam, __init__ 파일이 있다.
  • init 파일을 제외한 각 파일마다 패키지를 생성한다.
  • 주의 : import로 불러올 수 있는 파일은 패키지와 모듈만 가능하다. (클래스나 함수는 불가)
  • 하지만 from travel.thailand import ThailandPackage 구문은 가능하다.

3. _all_

from travel import *
trip_to = vietnam.VietnamPackage()
trip_to.detail()
  • __init__ 파일에 '__all__ = ["vietnam"]'을 작성
  • travel 폴더 전체를 돌려도 init 파일에 vietnam이 설정되어있기 때문에 vietnam 패키지의 디테일 값만 출력한다.

4. 모듈 직접 실행

if __name__ == "__main__":
    print("Thailand 모듈을 직접 실행")
    trip_to = ThailandPackage()
    trip_to.detail()
else:
    print("Thailand 외부에서 모듈 호출")
  • 조건문을 이용하여 모듈이 잘 작동하는지 확인 용도
  • 해당 파일 내(thailand)에서 작동시키면 if절, 이외는 else절이 출력

5. 패키지, 모듈 위치

import inspect
import random
print(inspect.getfile(random))
 
  • 랜덤 모듈이 어느 위치에 있는지 파일 경로 정보를 알려준다.

6. pip install

  • 구글에 'pypi' 검색하여 들어간 사이트에서 기존에 있는 패키지 이용할 수 있다.
  • 원하는 패키지를 클릭하여 pip install ~ 이라고 적힌 것을 복사한다.
  • 복사한 내용을 터미널에 붙여넣기하면 자동으로 설치가 완료된다.
  • 터미널에 'pip list'라고 치면 현재 설치된 pip 목록을 확인할 수 있다.
  • pip show 패키지명을 입력하면 상세 정보를 확인할 수 있다.
  • pip install --upgrade 패키지명을 입력하면 최신 버전으로 업그레이드를 할 수 있다.
  • pip uninstall 패키지명을 입력하면 패키지를 제거할 수 있다. (y)

7. 내장함수

  • input - 사용자 입력을 받는 함수
  • dir - 어떤 객체를 넘겨줬을 때 그 객체가 어떤 변수와 함수를 가지고 있는지 표시(사용할 수 있는 것)
  • 구글에 'list of python builtins' 검색하여 들어간 사이트에서 파이썬 내에서 사용할 수 있는 내장함수들을 확인할 수 있다.

8. 외장함수

  • glob - 경로 내의 폴더/파일 목록 조회
  • 구글에 'list of python modules' 검색하여 들어간 사이트에서 외장함수 목록을 확인할 수 있다.

Quiz. 프로젝트 내에 나만의 시그니처를 남기는 모듈을 만드시오.

조건: 모듈 파일명은 byme.py로 작성

def sign():
    print("이 프로그램은 나도코딩에 의해 만들어졌습니다.")
    print("유튜브 : http://youtube.com")
    print("이메일 : nado@gmail.com")
import byme
byme.sign()

강의 메모, 복습용으로 작성된 글입니다.

728x90
반응형
LIST