JAVA를 잡아라!...

Python #09_모듈과 import 본문

Python

Python #09_모듈과 import

onivv 2024. 5. 10. 09:21

[ 함수 & 메서드 ]

  • 함수 : 주어(객체)가 없이 목적어만 갖는 것
    1) 내장 함수 2) 사용자 정의 함수
    C 기반으로 탄생한 함수
    파이썬은 이미 로직이 짜여진 함수들이 잘 만들어져있음
    ▶ 로직보다는 잘쓰는게 중요 ▶ 주석, 로그, 가독성 중요
  • 메서드 : 주어(객체)가 있는 함수 == 객체지향 가능
    JAVA 기반으로 탄생한 메서드
    (반복되는)상황, 프로젝트, 다양한 케이스 처리
    ▶ 재사용, 모듈화 ▶ 객체지향 유리

#01 모듈

  • 개발자들이 만들어 놓은 유용한 다양한 함수들이 있음
  • 함수 묶음 == "모듈", 라이브러리
  • 모듈(모듈안의 함수)을 사용하기 위해서는 "import"(다운로드, 설치, install) 해야함
  • 즉, 모듈은 변수나 함수 또는 클래스들을 모아 놓은 파일 == 파이썬 파일(.py)

import 이슈

 

※ 모듈의 사용

# 해당 모듈 전체 함수 import
import 모듈명
import 모듈명 as 모듈별칭

ex)
import random
import random as r
r.randrange(1, 10)

# 파일을 가볍게 하기 위해 모듈 중 함수만 import
# 극단의 효율을 고려했을 때
from 모듈명 import 함수명
from 모듈명 import 함수명1, 함수명2, 함수병3, ...
from 모듈명 import * == import 모듈명
from 모듈명 import 함수명 as 함수별칭

 

#02 표준 모듈

  • 별도의 설치 없이 import 후 바로 사용가능한 모듈

 

math 모듈

 

random 모듈

 

time 모듈

 

 datetime 모듈

 

 

#03 외부 모듈

  • 표준 모듈 외에 별도의 설치를 통해 사용할 수 있는 모듈
  • 파이썬을 설치할 때 함께 설치되지 않는 모듈들은 기본적으로 패키지(package) 형태로 배포
    모듈의 상위 개념으로 패키지(package)가 있음
    패키지란 모듈의 집합을 의미하며 간단하게 정리하면 모듈이 모여있는 디렉터리라고 할 수 있음

패키지 관리자

  • 외부 모듈을 사용하기 위해서는 모듈이 포함된 패키지를 추가로 설치해야 함
  • 패키지 관리자 "pip" 사용
    패키지의 추가나 삭제와 같은 작업을 수행
    파이썬 설치 시 Add python.exe to PATH 체크했으면 바로 "pip" 사용 가능

명령 프롬프트에서 pip --help 명령을 이용해 pip 명령과 옵션을 확인 가능
pip install numpy 명령으로 numpy 패키지 설치
numpy 함수 사용 예제
pip uninstall numpy 명령으로 numpy 패키지 삭제

 

++ 행렬 생성 및 연산

# 행렬 생성
a = np.array([[1,2],[3,4]])     # array() 함수 : 배열(array) 생성
print(type(a))
print(a)

b = np.asmatrix(a)              # asmatrix() 함수 : 배열(array) --> 행렬(matrix) 변환
print(type(b))
print(b)

c = np.matrix([[1,2],[3,4]])    # matrix() 함수 : 행렬(matrix) 생성
print(type(c))
print(c)

d = np.mat([[1,2],[3,4]])       # mat() 함수 : 행렬(matrix) 생성
# 실행 결과
<class 'numpy.ndarray'>
[[1 2]
 [3 4]]
<class 'numpy.matrix'>
[[1 2]
 [3 4]]
<class 'numpy.matrix'>
[[1 2]
 [3 4]]
<class 'numpy.matrix'>
[[1 2]
 [3 4]]

 

++ numpy.matrix 더 이상 권장 x, 대신 numpy.array 사용

https://numpy.org/doc/stable/user/numpy-for-matlab-users.html

 

NumPy for MATLAB users — NumPy v1.26 Manual

In NumPy, the basic type is a multidimensional array. Array assignments in NumPy are usually stored as n-dimensional arrays with the minimum type required to hold the objects in sequence, unless you specify the number of dimensions and type. NumPy performs

numpy.org

 

# 행렬 연산
a_matrix = np.matrix([[1, 2], [3, 8], [10, 6]])     # matrix() a 행렬 생성
b_matrix = np.matrix([[1, 0], [1, 2]])              # matrix() b 행렬 생성
c_matrix = a_matrix * b_matrix                      # 행렬 곱 연산
print(type(c_matrix))                               # matrix type 출력
print(c_matrix)                                     # 연산 결과 출력

a_array = np.array([[1, 2], [3, 8], [10, 6]])       # array() a 행렬 생성
b_array = np.array([[1, 0], [1, 2]])                # array() b 행렬 생성
c_array = a_array @ b_array                         # 행렬 곱 연산
print(type(b_array))                                # array type 출력
print(c_array)                                      # 연산 결과 출력
# 실행결과
<class 'numpy.matrix'>
[[ 3  4]
 [11 16]
 [16 12]]
<class 'numpy.ndarray'>
[[ 3  4]
 [11 16]
 [16 12]]

'Python' 카테고리의 다른 글

Python #11_파일 입출력 (+ CSV)  (0) 2024.05.15
Python #10_파일 입출력 (+ 슬라이싱 Slicing)  (0) 2024.05.14
Python #08_사용자 정의 함수  (0) 2024.05.09
Python #07_메서드  (0) 2024.05.02
Python #06_내장 함수  (0) 2024.05.02