Table of Contents
파이썬 기초편 10강. 모듈과 패키지 #
실습코드 #
모듈 (Module) #
#!python
### 일반적인 모듈의 형태
# Define some variables:
numberone = 1
ageofqueen = 78
# define some functions
def printhello():
print("hello")
def timesfour(input):
print(input * 4)
# define a class
class Piano:
def __init__(self):
self.type = raw_input("What type of piano? ")
self.height = raw_input("What height (in feet)? ")
self.price = raw_input("How much did it cost? ")
self.age = raw_input("How old is it (in years)? ")
def printdetails(self):
print("This piano is a/an " + self.height + " foot",)
print(self.type, "piano, " + self.age, "years old and costing " + self.price + " dollars.")
모듈 import #
#!python
# 모듈 임포트 (moduletest.py)
>>> import moduletest
>>> moduletest.ageofqueen
78
>>> moduletest.printhello()
hello
# moduletest 모듈의 특정 변수, 함수만 임포트
>>> from moduletest import ageofqueen, timesfour
>>> timesfour(40)
160
>>> ageofqueen
78
사용자모듈 만들기 #
calc.py #
#!python
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
num1 = float(input('Enter your first number: '))
num2 = float(input('Enter your second number: '))
type_ = input('Enter type of operation (+, -, *, or /): ')
if type_ == '+':
print(add(num1, num2))
elif type_ == '-':
print(sub(num1, num2))
elif type_ == '*':
print(mul(num1, num2))
elif type_ == '/':
print(div(num1, num2))
else:
print("Invalid type of operation: '{}'".format(type_))
math 모듈 #
#!python
# math 모듈 임포트
>>> import math
>>> n = math.factorial(3)
>>> n
6
# math 모듈의 factorial() 함수만 임포트
>>> from math import factorial
>>> n = factorial(3)
>>> n
6
>>> factorial(4)
24
datetime 모듈 #
#!python
>>> import datetime
# 현재시간 출력
>>> datetime.datetime.now()
datetime.datetime(2017, 10, 2, 13, 49, 56, 842025)
>>> datetime.datetime.now().strftime('%Y-%m-%d')
'2017-10-02'
>>> datetime.datetime.now().strftime('%Y-%M-%D')
'2017-50-10/02/17'
# 원하는 정보 뽑아오기
>>> now = datetime.datetime.now()
>>> type(now)
<class 'datetime.datetime'>
>>> now.year
>>> now.month
10
>>> now.day
2
>>> mydate = datetime.date(2017, 11, 1)
>>> mydate
datetime.date(2017, 11, 1)
>>> mydate.year, mydate.month, mydate.day
(2017, 11, 1)
# 날짜 연산
>>> mydate + datetime.timedelta(days=365)
datetime.date(2018, 11, 1)
os 모듈 #
#!python
# 시스템 환경변수 확인
>>> import os
>>> os.environ
environ({'__CF_USER_TEXT_ENCODING': '0x1F5:0x3:0x33', 'LDFLAGS': … pw_pctjw0000gn/T/',})
# 디렉터리 위치 변경&확인
>>> os.getcwd()
'/Users/kobic/Downloads'
>>> os.chdir('../')
>>> os.getcwd()
'/Users/kobic'
# 시스템 명령어 실행
>>> f = os.popen('pwd')
>>> f.read()
'/Users/kobic\n'
# 디렉토리 생성, 삭제, 이름변경
>>> os.mkdir('dirname')
>>> os.rmdir('dirname')
>>> os.rename('oldname', 'newname')
# 파일삭제
>>> os.unlink('filename')
os.path 모듈 #
#!python
# 파일의 절대경로 반환
>>> os.path.abspath('path/to/file.txt')
'/Users/kobic/path/to/file.txt'
# 경로의 base name 반환
>>> os.path.basename('path/to/file.txt')
'file.txt'
# 두 경로의 공통경로 반환
>>> os.path.commonpath(['/home/kobic/file.txt', '/home/kobic/file2.txt'])
'/home/kobic'
# 디렉터리명 반환
>>> os.path.dirname('path/to/file.txt')
'path/to'
# 경로에 파일 혹은 디렉토리가 있는지 확인
>>> os.path.exists('./test')
True
# 파일 사이즈 반환 (bytes)
>>> os.path.getsize('./test')
68
# 파일경로 합치기
>>> os.path.join('/home', 'kobic', 'test', 'test.txt')
'/home/kobic/test/test.txt'
# 파일경로와 파일명으로 나누기
>>> os.path.split('path/to/file.txt')
('path/to', 'file.txt')
collection 모듈 #
defaultdict 사용 예 #
#!python
>>> colors = (
... ('Apple', 'Red'),
... ('Peach', 'Pink'),
... ('Banana', 'Yellow'),
... ('Apple', 'Green'),
... ('Banana', 'Green'),
... )
>>> colordict = defaultdict(list)
>>> for fruit, color in colors:
... colordict[fruit].append(color)
...
>>> print(colordict)
defaultdict(<class 'list'>, {'Peach': ['Pink'], 'Banana': ['Yellow', 'Green'], 'Apple': ['Red', 'Green']})
패키지 (Package) #
외부 라이브러리 설치하기 #
# pip search를 이용한 패키지 검색
$ pip search biopython
biopython-extensions (0.18.6) - Misc utilities and definitions not included or
hidden in BioPython
biopython (1.70) - Freely available tools for computational molecular
biology.
INSTALLED: 1.67
LATEST: 1.70
# pip를 이용한 biopython 설치
$ pip install biopython
연습문제 #
1번 #
다음은 dice.py 이다. (1)~(3) 물음에 답하시오. #!python import random
def play():
return random.randint(1, 6)
def predict(x):
val = random.randint(1, 6)
if val == x:
return 'Win!'
else:
return 'Lose! value: {}'.format(val)
- dice.py에서 play() 함수만 import할 수 있는 방법은?
- dice.py를 import하고 predict(2)를 실행하는 방법은?
2번 #
다음 패키지의 구조를 예측하시오. (1) ~ (4)안에 알맞은 값은 무엇인가?
#!python
>>> from Animal.dog import eat
>>> eat.banana(1)
>>> import Animal import sing
>>> sing()
'Lalalala...'
연습문제 풀이 #
1번 #
#!python
# (1)번 답
>>> from dice import play
>>> play()
2
# (2)번 답
>>> import dice
>>> dice.predict(2)
'Lose! value: 4'