[Python]모듈(module)에서 from, import, as 사용법

2020년 11월 01일 by 진아사랑해

    [Python]모듈(module)에서 from, import, as 사용법 목차
반응형

다른 화일에 필요한 함수들을 모아 놓은 것이 모듈(module)이다.

프로그램을 작성하면서 공통적으로 사용되는 함수들을 하나의 파일에 모아 놓을 수도 있다

 

theater_module.py 에

def price(people):

  print("{0}명의 영화 가격은 {1}입니다.,\" .format(people, people * 10000 )

 

def morning_price(people):

  print("{0}명의 조조할인 가격은 {1}입니다.,\" .format(people, people * 6000)

 

def soldier_price(people):

  print("{0}명의 조조할인 가격은 {1}입니다.,\" .format(people, people * 6000)

 

main.py 에서 

import theater_module  <- .py는 필요없음

이렇게 import를 하는 경우에는 theater_module.price( 3 ) 이렇게 파일명(모듈명)을 앞에 붙여야 함

 

import theater_module as tm <- theater_module 대신에 간략하게 tm이라는 별명으로 접근 가능

이 경우에는 tm.morning_price( 4 ) 이렇게 사용한다

 

from  theater_module import * 

from을 사용하는 경우에는 앞에 theater_module이 필요없이 바로 필요함수를 호출

soldier_price( 3 ) 이렇게 사용

 

from theater_module import price, morning_price

이 경우에는 price, morning_price 함수는 사용, solider_price 함수는 사용하지 못함

 

from theater_module import soldier_price as price  <- soldier_price 함수 이름에 price라는 별명 사용

price( 5 )  <- price 함수가 수행되는 것이 아니라 soldier_price 함수가 실행된다

 

참고영상: www.youtube.com/watch?v=kWiCuklohdY&t=4s

 

 

 

 

반응형