TIL - python(module)

한성봉·2021년 4월 18일

유튜브 '나도코딩'채널의 파이썬 강좌를 토대로 정리한 내용입니다.

Module(모듈)

  • 모듈이란 함수나 변수 또는 클래스를 모아 놓은 파일이다.
  • 모듈은 다른 파이썬 프로그램에서 불러와 사용할 수 있게끔 만든 파이썬 파일이라고도 할 수 있다.
  • 모듈은 다른 사람이 만든걸 쓸 수도 있고 직접 만들어 쓸 수도 있다.

모듈 예시를 들기 위해 theather_module.py이라는 파일이 하나 새로 생성하겠다.

1. 모듈 생성

# 일반 가격
def price(people):
    print("{0}명 가격은 {1}원입니다.". format(people, people * 100000))
# 조조 할인 가격
def price_morning(people):
    print("{0}명 가격은 {1]원입니다.". format(people, people * 6000))
# 군인 할인 가격
def price_soldier(people):
    print("{0}명 가격은 {1]원입니다.". format(people, people * 4000))

theather_module.py 파일에 함수 모듈을 생성하였다.
모듈을 불러와 작업하고 싶은 파일에서 모듈을 불러오는 예시를 한번 살펴보자.

2. 모듈 파일 불러오기

입력

import theather_module
theather_module.price(3)
theather_module.price_morning(4)
theather_module.price_soldier(5)

출력

3명 가격은 30000원입니다.
4명의 조조 할인 가격은 24000원입니다.
5명의 군인 할인 가격은 20000원입니다.

import theather_module 모듈을 불러오는 첫번째 방법이다.

모듈의 이름을 임의로 변경하여 원하는 이름으로 쓸 수 있다. 다음 예시를 살펴보자.

3. 모듈 파일 이름 변경

import theather_module as mv
mv.price(3)
mv.price_morning(4)
mv.price_soldier(5)

임의 변경한 모듈 이름을 사용하여도 위와 똑같은 결과값을 확인할 수 있다.

모듈을 불러오는 두번째 방법을 살펴보자.

4. 모듈 파일 불러오기(2)

from theather_module import *
price(3)
price_morning(4)
price_soldier(5)

모듈을 불러오는 두번째 방법은 from theather_module import *이다.
두번째 방법으로 모듈을 불러오면 모듈 이름 없이 함수 이름만 쓰면 사용 가능하다.

5. 모듈 내 필요한 기능만 불러오기

from theather_module import price, price_morning
price(3)
price_morning(4)

만약 불러올 함수를 지정해놓고 지정하지 않은 함수를 불러올려고 하면 NameError: name 'price_soldier' is not defined NameError```가 발생한다.

6. 모듈 내 필요한 기능만 불러오고, 모듈 이름 임의변경

입력

from theather_module import price_soldier as price
price(10)

출력

10명의 군인 할인 가격은 40000원입니다.

모듈에서 불러온 함수의 이름을 다른 함수의 이름과 동일하게 변경하여도 불러온 함수가 사용된다.

0개의 댓글