모듈과 패키지 만들기
모듈 만들기
# square2.py
base = 2 # 변수
def square(n): # 함수
return base ** n
모듈 사용
# main.py
# import 모듈
# 모듈.변수
# 모듈.함수()
import square2
print(square2.base)
print(square2.square(10))
# 실행 결과
2
1024
from import로 변수, 함수 가져오기
# from 모듈 import 변수, 함수
from square2 import base, square
print(base)
print(square(5))
# 실행 결과
2
32
모듈에 클래스 작성
# person.py
class Person: # 클래스
def __init__(self, name, age, addr):
self.name = name
self.age = age
self.addr = addr
def greeting(self):
print('안녕하세요. 저는 {}입니다.'.format(self.name))
# main.py
import person
maria = person.Person('마리아', 20, '수원')
maria.greeting()
# 실행 결과
안녕하세요. 저는 마리아입니다.
from import로 클래스 가져오기
from person import Person
james = Person('제임스', 20, '제주')
james.greeting()
# 실행 결과
안녕하세요. 저는 제임스입니다.
모듈과 시작점 알아보기
if __name__ == '__main__':
코드
위 코드를 사용하는 이유?
# __name__
# hello.py
print('hello 모듈 시작')
print('hello.py __name__:', __name__) # name 변수 출력
print('hello 모듈 끝')
# main.py
import hello
print('main.py __name__:', __name__) # __name__ 변수 출력
# 실행 결과
hello 모듈 시작
hello.py __name__: hello
hello 모듈 끝
main.py __name__: __main__
실행해 보면 hello.py 파일과 main.py 파일의 __name__ 변숫값 출력
파이썬에서 import로 모듈 가져오면 해당 스크립트 파일이 한 번 실행
어떤 스크립트 파일이든 파이썬 인터프리터가 최초로 실행한 스크립트 파일의 __name__에는 '__main__'이 들어감
> 프로그램의 시작점(entry point)
파이썬은 최초로 시작하는 스크립트 파일과 모듈의 차이가 없음
어떤 스크립트 파일이든 시작점이 될 수도 있고, 모듈도 될 수 있음
> __name__ 변수를 통해 현재 스크립트 파일이 엔트리 포인트인지 모듈인지 판단
if __name__ == '__main__':
코드
> 현재 스크립트 파일이 프로그램의 엔트리 포인트가 맞는지 판단하는 작업
> 스
스크립트 파일로 실행하거나 모듈로 사용하는 코드 만들기
# clac.py
def add(a, b):
return a + b
def mul(a, b):
return a * b
if __name__ == '__main__':
print(add(10, 20))
print(mul(10, 20))
# 터미널 창 실행 결과
PS C:project\basic> python clac.py
30
200
PS C:project\basic> py
>>> import clac
>>>
>>> clac.add(50, 60)
110
>>> clac.mul(50, 60)
3000
>>>
import clac에서 30, 200이 출력되지 않은 이유는 main이 아니기 때문
패키지 만들기
패키지 폴더 구성
project
> main.py
> calcpkg
> __init__.py
> operation.py
> geometry.py
# __init__.py 파일은 내용을 비워 둘 수 있음
파이썬 3.3 이상부터는 __init__.py 파일이 없어도 패키지로 인식되지만 하위 버전에도 호환되도록 작성 권장
패키지에 모듈 만들기
# operation.py
def add(a, b):
return a + b
def mul(a, b):
return a * b
# geometry.py
def triangle_area(base, height):
return base * height / 2
def rectangle_area(width, height):
return width * height
패키지 사용
# import 패키지.모듈
# 패키지.모듈.변수
# 패키지.모듈.함수()
# 패키지.모듈.클래스()
import calcpkg.operation
import calcpkg.geometry
print(calcpkg.operation.add(10, 20))
print(calcpkg.operation.mul(10, 20))
print(calcpkg.geometry.triangle_area(30, 40))
print(calcpkg.geometry.rectangle_area(30, 40))
# 실행 결과
30
200
600.0
1200
from import로 패키지의 모듈에서 변수, 함수, 클래스 가져오기
from 패키지.모듈 import 변수
from 패키지.모듈 import 함수
from 패키지.모듈 import 클래스
>>> from calcpkg.operation import add, mul
>>> add(10, 20)
30
>>> mul(10, 20)
200
모듈과 패키지를 찾는 경로
>>> import sys
>>> sys.path
['',
'C:\\Users\\user\\anaconda3\\python311.zip',
'C:\\Users\\user\\anaconda3\\DLLs',
'C:\\Users\\user\\anaconda3\\Lib',
'C:\\Users\\user\\anaconda3',
'C:\\Users\\user\\anaconda3\\Lib\\site-packages',
'C:\\Users\\user\\anaconda3\\Lib\\site-packages\\win32']
패키지에서 from import 응용
from . import 모듈
# __init__.py
from . import operation # 현재 패키지에서 모듈을 가져옴
from . import geometry # . < 현재 패키지라는 뜻
. < 현재 폴더
.. < 상위 폴더
# main.py
import calcpkg # calcpkg 가져오기
# import calcpkg.operation
# import calcpkg.geometry
print(calcpkg.operation.add(10, 20))
print(calcpkg.operation.mul(10, 20))
print(calcpkg.geometry.triangle_area(30, 40))
print(calcpkg.geometry.rectangle_area(30, 40))
# 실행 결과
30
200
600.0
1200