-
Python 문법 기초 22 - 모듈(module)Python 2022. 10. 22. 16:50
모듈을 모은 것이 라이브러리 그것들이 모인 것이 프레임워크이다.
Module : 소스 코드의 재사용을 가능하게 할 수 있으며, 소스코드를 하나의 이름공간으로 구분하고 관리하게 된다.
하나의 파일은 하나의 모듈이 된다.
표준모듈, 사용자 작성 모듈, 제3자(Third party) 모듈
모듈의 멤버 : 전역변수, 실행문, 함수, 클래스, 모듈
a = 10 print(a) def abc(): print('abc는 모듈의 멤버 중 함수') abc() <console> 10 abc는 모듈의 멤버 중 함수
# 표준모듈(내장된 모듈 읽기) import math print(math.pi) print(math.sin(math.radians(30))) import calendar calendar.setfirstweekday(6) # 0~6으로 되어있으며 0은 월요일부터 시작이다. calendar.prmonth(2022, 10) import os // 현재 경로 위치 호 print(os.getcwd()) print(os.listdir('/')) <console> 3.141592653589793 0.49999999999999994 October 2022 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 C:\Users\JEONGYEON\Desktop\Python\에어컨 빵빵한 에이콘 Python\pro1\pack2 ['$Recycle.Bin', '$WinREAgent', 'anaconda3', 'AVScanner.ini', 'Daum Games', 'Documents and Settings', 'Download', 'DumpStack.log.tmp', 'hiberfil.sys', 'java', 'OneDriveTemp', 'oraclexe', 'pagefile.sys', 'PerfLogs', 'Program Files', 'Program Files (x86)', 'ProgramData', 'Recovery', 'Riot Games', 'swapfile.sys', 'System Volume Information', 'Users', 'Windows', 'Windows.old']
내장된 모듈을 import를 사용하여 호출하여 쓰는 방법이다.
import random print(random.random()) print(random.randint(1, 10)) from random import random print(random()) from random import randint, randrange print(randint(1, 10)) from random import * <console> 0.8104623135173338 3 0.07978967552570526 1
from import 형식의 방법도 있다.
*를 사용하여 random 안의 모든 함수들을 가져올 수도 있지만 함수들이 전부 로딩되기때문에 메모리 낭비가 심해서 사용할 경우 충분히 조심해야한다.
사용자 작성 모듈
# 메인으로 사용하지 않고 다른 모듈에 호출될 멤버를 기술하는 용도 # 선언만 해둔 상태이다. 호출 x price = 12345 def listHap(*ar): print(ar) if __name__ == '__main__': print('난 최상위 메인 모듈이야') def kbs(): print('대한민국 대표방송') def mbc(): print('만나면 좋은 친구')
# 사용자 작성 모듈 print('뭔가를 하다가...') # 다른 모듈의 멤버 호출 list1 = [1, 3] list2 = [2, 4] import pack2.mymodule1 pack2.mymodule1.listHap(list1, list2) print(pack2.mymodule1.__file__) // 경로 위치 호출 print(pack2.mymodule1.__name__) // 파일 이름 호 <console> 뭔가를 하다가... ([1, 3], [2, 4]) C:(앞에건 보호)Python\pro1\pack2\mymodule1.py pack2.mymodule1
자신이 만든 모듈을 import 할 수 있다.
def abcd(): if __name__ == '__main__': print('난 메인 모듈이야') abcd() <console> 난 메인 모듈이야
java에서는 main 모듈이 따로 있었지만 파이썬에서는 그러한 것이 없기 때문에 가독성이 매우 떨어진다. 그러므로 위의 함수를 적어 메인 모듈인지 확인하는 작업을 해주는 것이 좋다.
print('가격은 {}원'.format(pack2.mymodule1.price)) from pack2.mymodule1 import price print('가격은 {}원'.format(price)) from pack2.mymodule1 import kbs, mbc kbs() mbc() <console> 가격은 12345원 가격은 12345원 대한민국 대표방송 만나면 좋은 친구
price를 자주 사용할 것 같으면 밑에거를 사용하는 것도 추천한다.
다만 mymodule1 안의 함수를 모두 사용할 것 같으면 위에 것을 추천.
print('\n다른 패키지에 있는 모듈 읽기') import etc.mymodule2 print(etc.mymodule2.Hap(5, 3)) from etc.mymodule2 import Cha print(Cha(5, 3)) <console> 다른 패키지에 있는 모듈 읽기 8 2
자신이 만든 모듈을 이 경로에 넣어주면 호출해서 사용할 수 있다.
이클립스에서는 지워도 상관없음.
print('\n다른 패키지(path가 설정된)에 있는 모듈 읽기') import mymodule3 print(mymodule3.Gop(5, 3)) from mymodule3 import Nanugi print(Nanugi(5, 3))
이렇게 호출이 가능하다.
모듈은 위의 경로 이외에도 위의 경로 중 아무곳에나 넣어도 사용 가능.
바로 import 해서 사용 가능.
새로운 폴더를 추가해도 상관없음.
def Gop(a, b): return a * b def Nanugi(a, b): return a / b # 아나콘다 폴더 안의 라이브러리 등 이 모듈을 이동시키고 나서는 # import 만으로도 호출이 가능하다. # 이동 후에는 이클립스에서는 확인 가능하다.
예제 1) turtle로 도형 그리기
# 파이썬 제공 그래픽 라이브러리(모듈들의 집합) # turtle로 도형 그리기 from turtle import * p = Pen() p.color('red', 'yellow') p.begin_fill() while True: p.forward(200) p.left(170) if abs(p.pos()) < 1: break p.end_fill() done()
3.10.8 Documentation
Python 3.10.8 documentation Welcome! This is the official documentation for Python 3.10.8. Parts of the documentation: What's new in Python 3.10? or all "What's new" documents since 2.0 Tutorial start here Library Reference keep this under your pillow Lang
docs.python.org
사이트에서 라이브러리 들어가면 원하는 라이브러리를 찾을 수 있다.
샘플도 있으니 위처럼 가져와서 Pen의 클래스를 호출해서 적용시켜주면 바로 사용 가능하다.
제 3자 모듈 사용
1. Anaconda Prompt 에 들어가서
2. pip install pygame(깔고싶은 모듈) 을 입력한다.
그럼 위 처럼 버전에 맞게 알아서 깔린다.
3. pip install pygame이 되지 않으면 conda install pygame을 사용하면 된다.
둘 다 안 될 경우 밑의 사이트로 이동해서 직접 다운받는다.
Python 참고문서 및 참조 사이트
파이썬으로 할 수 있는 일- 시스템 유틸리티 제작- GUI 프로그래밍- C/C++와의 결합- 웹 프로그래밍- 수치 연산 프로그래밍- 데이터베이스 프로그래밍- 데이터 분석, 사물 인터넷- 네크워킹파이썬으
cafe.daum.net
이곳에서도 버전별로 검색 가능하다.
opencv 이미지/영상/동영상 처리
# opencv(Computer vision) : 이미지/영상/동영상 처리에 사용할 수 있는 오픈 소스 라이브러리 # pip install opencv-python import cv2 # print(cv2.__version__) # 이미지 읽기 img1 = cv2.imread('./sajin.jpg') print(type(img1)) # img1 = cv2.imread('./sajin.jpg', cv2.IMREAD_COLOR) # 채널(channel) : 3 (R,G,B) # img1 = cv2.imread('./sajin.jpg', cv2.IMREAD_GRAYSCALE) # 채널(channel) : 1 img1 = cv2.imread('./sajin.jpg', cv2.IMREAD_COLOR) cv2.imshow('image test', img1) cv2.waitKey() cv2.destroyAllWindows() # 이미지를 다른 이름으로 저장 cv2.imwrite('./sajin2.jpg', img1) # 이미지 크기 조절 img2 = cv2.resize(img1, (320,100), interpolation=cv2.INTER_AREA) cv2.imwrite('./sajin3.jpg', img2) # 이미지 상하좌우 대칭 (Flip) # a = cv2.imshow('image rotation', cv2.flip(img1, flipCode=0)) 이미지 뒤집기 a = cv2.imshow('image rotation', cv2.flip(img1, flipCode=1)) # 이미지 좌우대칭 cv2.waitKey() cv2.destroyAllWindows()
'Python' 카테고리의 다른 글
Python 문법 기초 24 - class 포함관계(1) (0) 2022.10.22 Python 문법 기초 23 - class(import 사용) (0) 2022.10.22 Python 문법 기초 21 - 재귀 함수(Recursive function) (0) 2022.10.22 Python 문법 기초 20 - 함수 장식자(decorator) (0) 2022.10.22 Python 문법 기초 19 - 일급함수와 람다함수 (0) 2022.10.22