728x90
반응형
파이썬 파일에서 다른 파이썬 파일을 불러와 사용하는 것을 모듈이라고 한다.
단, 같은 경로(폴더)에 있을 때만 불러올 수 있다. (방법이 따로 있음)
1) calculator.py
def add(x,y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
2) calculator.py
# 'calculator'라는 파이썬 파일을 불러오겠다.
import calculator
print(calculator.add(5, 3))
#결과
8
print(calculator.multiply(3, 4))
#결과
12
#calculator를 불러올 때 calc 라는 이름으로 지정하여 불러오겠다.
import calculator as calc
print(calc.add(2, 5))
#결과
7
print(calc.add(3, 4))
#결과
12
#모듈에서 add 함수와 multiply 함수만 불러오겠다.
from calculator import add, multiply
print(add(2, 5))
#결과
7
print(multiply(3, 4))
#결과
12
#모듈에 있는 모든 함수를 불러 오겠다.
from calculator import *
-> 권장하지 않는 방식, 어떤 파일에 있는 함수를 불러왔는지 모를 수 있기 때문에
728x90
반응형
'TIL > Python' 카테고리의 다른 글
[파이썬] datetime 모듈 (0) | 2021.02.22 |
---|---|
[파이썬] random 모듈 (0) | 2021.02.22 |
[파이썬] 리스트와 문자열 정리 (0) | 2021.02.22 |
[파이썬] Aliasing(가명) (0) | 2021.02.15 |
[파이썬] 사전 활용법(dict) (0) | 2021.02.15 |