Python Basic _ 6-2. 파이썬 모듈

WONY_yoon·2025년 10월 3일
post-thumbnail

Python Module 알아보기

# chapter06-2
# 파이썬 모듈
# Module : 해당 기능만 딱! / 함수, 변수, 클래스 등 파이썬 구성요소를 모아놓은 파일

def add(x, y):
    return x + y

def sub(x, y):
    return x - y

def mul(x, y):
    return x * y

def div(x, y):
    return x / y

def pow(x, y):
    return x ** y

# print('-' * 15)
# print('called inner!')
# print(add(5,5))
# print(sub(15,5))
# print(mul(5,5))
# print(div(10,2))
# print(pow(5,3))
# print('-' * 15)

# 예약어
# __name__ : 모듈의 이름을 담고 있는 내장 변수
# → 해당 파일이 직접 실행되면 '__main__'
# → 다른 파일에서 import 하면 모듈 이름이 들어옴

if __name__ == '__main__':
    print('-' * 15)
    print('called __main__!')
    print(add(5,5))     # 10
    print(sub(15,5))    # 10
    print(mul(5,5))     # 25
    print(div(10,2))    # 5.0
    print(pow(5,3))     # 125
    print('-' * 15)

# 출력 결과 (이 파일을 직접 실행했을 경우)
# ---------------
# called __main__!
# 10
# 10
# 25
# 5.0
# 125
# ---------------

Module Test 해보기

# 모듈 사용 실습

import sys
import time

print(sys)  
# <module 'sys' (built-in)>

print(sys.path)  
# 파이썬이 모듈을 탐색하는 경로 리스트 출력
# 예: ['/usr/lib/python3.11', '/usr/lib/python3.11/lib-dynload', ...]

print(type(sys.path))  
# <class 'list'>

# type 형식이 list 이므로 append 사용하여 추가 가능
sys.path.append('/Users/cybersecurity_123/Desktop/인프런/python basic/실습용')

print(sys.path)  
# 기존 sys.path 리스트에 경로가 추가되어 출력됨

import test_module  # 같은 폴더에 있는 test_module.py 불러옴

print(test_module.pow(9,3))    # 729

실행 흐름 요약

  1. sys 모듈 자체와 sys.path(모듈 탐색 경로 리스트)가 출력됨.
  2. sys.path.append(...) 로 사용자 경로를 추가 → 이제 그 경로 안의 .py 파일을 import 가능.
  3. import test_module 실행 → 방금 만든 chapter06-2test_module.py 불러옴.
  4. print(test_module.pow(9,3))pow(9,3) = 9 ** 3 = 729 출력.

0개의 댓글