특정기능을 가지고 있는 파이썬 파일
e.g. random.py
이미 만들어진 기능으로 사용자가 쉽게 사용할 수 있다.
import 모듈명
e.g. random calculator
- 파이썬파일 만들기
- 해당파일에 def로 함수만들기
- 실행파일에서 import.파이썬파일이름
단, 같은 폴더(Directory)에 있어야한다.
e.g. module 이라는폴더에 reverseStr 라는 함수를 만들고 실행파일에서 실행 시
(문자를 입력하면 거꾸로 출력되는 함수)
#module폴더의 reverseStr모듈
#directory : module / 파일명 : reverseStr.py
def reverseStr (str): #함수명
str = ''
return str[::-1]
#실행파일에서
from module import reverseStr as r
print(r.reverseStr('python'))
# nohtyp
이때 calculator라는 모듈명이 너무 길다면,
as를 사용해서 별명으로 출력할 수 있다.from 폴더명 import 모듈명 as 별명
from module import calculator as cal
cal.add(10,20)
cal.sub(10,20)
cal.mul(10,20)
cal.div(10,20)
파일명 사용할 필요없이 기능을 바로 사용가능하다.
from 모듈명.함수명 import 기능명
from module.reverseStr import reverseStr as r
print(r('python')) #바로 기능 사용 가능
점수를 입력하면 총점과 평균을 구하는 모듈을 만들어보자
#module directory의 score.py
scores = []
def score_add(*s):
for i in s :
scores.append(i)
def score_get():
return scores
def score_sum() :
return sum(scores)
def score_avg():
return sum(scores) / len(scores)
#실행파일
from module import score as sc
kor = int(input('국어 점수 입력 : '))
eng = int(input('영어 점수 입력 : '))
math = int(input('수학 점수 입력 : '))
sc.score_add(kor,eng,math)
print(sc.score_get()) #[50, 80, 90]
print(sc.score_sum()) #220
print(sc.score_avg()) #73.33333333333333
실행파일의 위치를 찾고자 할때 전역변수
__name__
를 사용한다.
print(__name__)
위 코드를 출력할 때, 실행파일이라면
'__main__'
이라고 출력된다.
<예시>
만약, module파일의 score모듈에 위 코드를 코딩하고,
score파일을 import하는 실행파일에서 코드를 실행할 경우
score파일의 출력물이 실행파일에서도 출력된다.
그때, score파일의
__name__
은 'module.score'로 출력된다. (실행파일이 아니기때문)
📢 모듈의 출력값이 실행파일에 출력되지 않게 하고싶다면?
if __name__ == '__main__'
print('실행파일일 때만 출력해줘')
e.g. 위의 예시에서 사용한 모듈들을 같은 directory에 넣어놓는것
site-packages에 있는 모듈은 어디에서나 사용할 수 있다.
(from directory명을 해주지 않아도 됨)
📢 폴더에 구애받지 않고 사용하고싶다면
python 내 venv -> Lib -> site-packages 에 파일을 만들고 모듈을 생성하면 어드 폴더에서나 사용할 수 있다. (기본 제공 모듈[내장함수]도 모두 해당파일에 담겨있다)
📢 모듈이 어느 directory에 있는지 알고 싶다면
import sys
for path in sys.path :
print(path)
venv -> Lib -> site-packages에 있는 모듈
sum() : 합
max() : 최대값
min() : 최소값
pow(x,y) : x의y제곱
round(x,n) : x의 n번째까지 반올림
abs() : 절댓값
math.fabs() : 절댓값
math.ceil() : 올림
math.floor() : 내림
math.trunc() : 버림
math.gcd(x,y) : x,y의 최대공약수
math.factorial(x) : x의 팩토리얼
math.sqrt(x) : 루트x
math.sum() :
time.locatime() : 현재 시간정보
time.locatime().tm_year : 년
time.locatime().tm_mod : 월
time.locatime().tm_mday : 일
time.locatime().tm_hour : 시
time.locatime().tm_min : 분
time.locatime().tm_sec : 초
random.random() : 0이상 1미만 난수
random.randrange(x,y) : x이상 y미만 난수 random.sample((범위),개수) : 범위내에서 지정개수만큼 난수생성
모듈관련해서는 추후 따로 정리하여 벨로그 업로드예정