kisti 기반기술개발실 - scent.gist.ac.kr · • python cookbook...

Post on 27-Aug-2018

233 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

김상완KISTI 기반기술개발실E-mail: sangwan@kisti.re.kr

2010년 5월 28일제1차 PLSI 광주/전남지역 선도 거점 슈퍼컴퓨팅센터 활성화 워크숍

목차

• 파이썬 언어 소개

• 파이썬 설치

• 파이썬 시작하기

• 자료형과 연산자

• 기본문

• 함수 (function)• 클래스 (class)• 예외 (exception)• 모듈 (module)• 파일처리 (file)• 직렬화 (serialization)

2Python 기초 교육

파이썬의 장점

4Python 기초 교육

파이썬의 장점

5Python 기초 교육

파이썬의 장점

6Python 기초 교육

파이썬은 어떤 언어인가?파이썬 = “객체지향 스크립트 언어”• 객체지향 언어(object-oriented language)

– 클래스 모델 언어에서 지원하는 다형성(polymorphism), 연산자 중복(operator overloading), 다중 상속(multiple inheritance) 개념을 지원

– 다른 OOP 언어에 배해 파이썬이 훨씬 배우기 쉽다

– 접착 코드(glue code)를 이용하여 C++이나 Java로 구현된 클래스를 상속 받을 수 있다

– OOP는 파이썬에서는 선택사항: 객체 사용에 익숙치 않아도 작업 가능

• 무료언어: 파이썬은 프리웨어(freeware)– 오픈 소스 소프트웨어: 인터넷에서 다운 가능, 시스템에 내장해서 또는 포함해서 생간할 수 있으

며 원한다면 상업적으로 판매할 수도 있다.

• 강력한 이식성

– 이식성이 강한 ANSI C로 작성: 주요 모든 플렛폼에서 컴파일과 실행가능: UNIX, MS-DOS, Windows, Mac, Amiga, Be-OS, OS/2, VMS, QNX 등

– 이식 가능한 바이트코드(bytecode)로의 자동 컴파일

– Tkinter라고 하는 ‘Tk GUI 시스템 표준 인터페이스’를 포함한다. X윈도우 시스템, MS 윈도우, 매킨토시에서 동일하게 수행. 모든 플랫폼에서 프로그램 수정 없이 수행가능

Guido van Rossum(파이썬 창시자)

7Python 기초 교육

파이썬은 어떤 언어인가?• 강력하다

– 파이썬은 혼합 언어이다. 전통적인 스크립트 언어(티클, 펄, 스킴(Scheme))와 시스

템 언어(C, C++, 자바)의 중간에 위치.– 동적형결정(dynamic typing): 실행시에 프로그램이 사용하는 객체의 종류를 추적

한다. 소스 코드에 데이터형과 크기를 복잡하게 선언할 필요가 없다.– 내장 객체 자료형: 자주 사용하는 리스트, 사전, 문자열 등의 자료구조를 언어 내장의

기본 자료구조로 제공한다.– 내장 도구: 객체 자료형을 처리하기 위하여 강력하고 표준적인 연산을 제공한다. 붙

이기, 슬라이싱, 정렬, 매핑등

– 라이브러리 유틸리티: 전문화된 작업을 위해서 미리 만들어진 많은 라이브러리 도구

를 제공. 정규식(regular-expression)에서 객체 유지 네트워킹(object persistence networking)에 이르기 까지.

– 서드파티 유틸리티: 개발자는 작업을 지원하는 도구를 만들어 기여할 수 있음.– 자동 메모리 관리: 자동으로 메모리를 할당하고, 더 이상 사용되지 않을 때 회수한다.– 대형 프로그래밍 지원: 큰 시스템을 구축하는데 필요한 모듈, 클래스, 그리고 예외 상

황과 같은 도구를 지원.

8Python 기초 교육

파이썬은 어떤 언어인가?• 혼합이 가능하다

– 다른 언어로 쓰여진 컴포넌트와 쉽게 붙는다(glued). 파이썬 프로그램을 C언어나

C++로 쓰여진 컴포넌트로 확장할 수 있고, 임베딩(embedding) 또한 가능하다. 사용하기 쉬운 종단 언어(frontend language) 및 커스터마이즈 도구(customize tool)로 활용 가능.

– 빠른 프로토타입 제작에 활용 가능. 빠른 개발 속도로 파이썬 시스템을 구현하고, 나중에 성능 요구가 필요하다면 한번에 하나씩 C언어로 변환.

– 윈도우를 위한 PythonWin은 COM API로 쓰여진 다른 컴포넌트와 파이썬 프로그램

이 대화할 수 있도록 한다. 파이썬의 또 다른 대체 언어로 Jpython이 있으며 자바 프

로그램과 연결. (자바 기반 웹 응용 프로그램의 스크립트를 작성)

• 사용하기 쉽다 / 배우기 쉽다

– 빠른 작업 전환 시간(turnaround)과 언어의 단순성은 재미를 준다

– 컴파일과 링크 단계가 없고, 대화식으로 프로그램의 실행 및 변경과 빠른 작업 전환

이 가능.– 참고) 파이썬 프로그램은 바이트코드라고 하는 중간 형태로 컴파일되면, 인터프리터

는 이것을 가지고 수행한다. 바이트코드로 컴파일 단계는 프로그래머에게 숨겨 진다.

9Python 기초 교육

파이썬은 어떤 언어인가?• 작업을 위한 파이썬

– 시스템 유틸리티: 운영체제 서비스에 대한 내장 인터페이스를 활용하여 유지보수 가

능한 시스템 관리 도구로 활용가능. (쉡스크립트 형태). 환경변수, 파일, 소켓, 파이

프, 프로세스, 쓰레드, 정규식 등을 지원

– GUI: Tkinter라는 Tk GUI API로 표준 객체지향 인터페이스를 지원.

• 이식석이 중요하지 않다면, 위도우의 PythonWin을 이용한 MFC 클래스나 유닉스의 X윈도

우 시스템 인터페이스, 매킨토시에서 Mac의 도구 박스 및 리눅스의 KDE와 GNOME을 사

용할 수 있다. 웹 브라우져에서 실행되는 응용 프로그램을 위해 JPython을 선택할 수도 있

다.

– 컴포넌트 결합

– 빠른 프로토타입 만들기

– 인터넷 스크립팅: CGI, XML처리, FTP등 지원

– 수치연산 프로그래밍: NumPy 모듈

– 데이터베이스 프로그래밍

– 그 외의 작업: 이미지 처리, AI, 분산 객체 등10Python 기초 교육

파이썬이 사용된 상용 제품

• 레드헷 아나콘다: 리눅스 설치 도구

• 마이크로소프트에서 파이썬으로 작성된 일부 제품을 내놓음

• Infoseek에서 웹 검색 제품에 일반 사용자 커스텀 언어로 파이썬을 사용함.• 야후는 다양한 인터넷 서비스에 파이썬을 사용한다.• NASA는 파이썬을 임무 제어 시스템에 사용한다

• 로렌스 리버모어 연구소는 다양한 수치 연산 프로그래밍 작업에 파이썬을사용한다.

• Industrial Light and Magic 및 다른 업체는 파이썬을 광고용 애니메이션을 만들기 위해 사용하고 있다.

기타) 파이썬 관련 웹사이트(www.python.org)를 보면 파이썬을 사용하는 좀더 많은 업체의 최신 목록을 볼 수 있다.

11Python 기초 교육

참고서적

• Learning Python (파이썬시작하기)– 마크루츠, 데이비드 애셔 저

– 이강성 역

– 1999년 4월– 384 pages

http://www.hanbitbook.co.kr/look.php?isbn=1-56592-464-9 12Python 기초 교육

참고서적

• Programming Python, 2nd Edition– By Mark Lutz– March 2001– 1296 pages

http://www.oreilly.com/catalog/python2/index.html 13Python 기초 교육

파이썬 관련 참고 사이트

• Python Cookbook (다양한 예제들이 많이 있음)– http://aspn.activestate.com/ASPN/Python/Cookbook/

14Python 기초 교육

파이썬 관련 참고 사이트• Dive Into Python

– http://diveintopython.org/

15Python 기초 교육

http://www.python.org/

17Python 기초 교육

18Python 기초 교육

윈도우용 파이썬 설치 (WindowsXP)python-2.6.5.msi (14MB) 다운로드 후 실행

19Python 기초 교육

내 컴퓨터->등록정보PATH 변수에 추가함(세미콜론(;)으로 구분)c:\python26

윈도우용 파이썬 설치 (WindowsXP)

20Python 기초 교육

시작메뉴 -> 실행 -> cmd 실행

윈도우용 파이썬 설치 (WindowsXP)

21Python 기초 교육

mkdir /usr/local/src/pythoncd /usr/local/src/python

wget http://www.python.org/ftp/python/2.6.5/Python-2.6.5.tgz

tar zxvf Python-2.6.5.tgzcd Python-2.6.5

./configure --help

./configure --prefix=/usr/local/python265 2>&1 | tee c.log(참고) --enable-unicode(참고) readline-devel 패키지가 설치되어 있는지 확인 (인라인 컴맨드 편집)

make 2>&1 | tee make.log

make install 2>&1 | tee install.log

소스를 컴파일 설치 (Linux)

22Python 기초 교육

# 기존에 설치된 python을 새로 설치한 것으로 바꿈mv /usr/bin/python /usr/bin/python.oldln -s /usr/local/python265/bin/python /usr/bin/python

# 설치확인# /usr/local/python265/bin/pythonPython 2.6.5 (r265:79063, May 28 2010, 01:17:49)[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>>

소스를 컴파일 설치 (Linux)

23Python 기초 교육

[root@localhost /usr/local/python2.4.2]# tree -d.

|-- bin|-- include| `-- python2.4

|-- lib| `-- python2.4| |-- bsddb| | `-- test| |-- compiler| |-- config| |-- curses| |-- distutils| | |-- command| | `-- tests| |-- email| | `-- test| | `-- data| |-- encodings| |-- hotshot| |-- idlelib| | `-- Icons| |-- lib-dynload| |-- lib-old| |-- lib-tk| |-- logging| |-- plat-linux2

| |-- site-packages| | |-- MySQLdb| | | `-- constants| | `-- mod_python| |-- test| | |-- decimaltestdata| | `-- output| `-- xml| |-- dom| |-- parsers| `-- sax`-- man

`-- man1

설치된 파이썬의 디렉토리 구조 참고

24Python 기초 교육

Interactive Input Editingand History Substitution • 라인 편집

– CTRL-A/E: 줄의 맨 처음/끝으로 커서를 옮김

– CTRL-B/F: 왼쪽/오른쪽으로 커서를 옮김

– BackSpace/CTRL-D: 커서 왼쪽/오른쪽의 글자를 지움

– CTRL-K (kill): 커서의 오른쪽부터 줄의 맨 끝까지 삭제하고 버퍼에 복사

– CTRL-Y (yank): 퍼버에 복사된 내용을 붙임

– CTRL-_(underscore): 마지막으로 한 동작을 취소함

• 자동완성

– 파이썬 인터렉티브 모드에서 변수명, 모듈명을 자동완성 하는 기능을 이용하려면 다음 라인을 $PYTHONSTARTUP 파일에 추가한다.

Python Tutorial Appendix A 참조

import rlcompleter, readlinereadline.parse_and_bind('tab: complete')

– Tab키는 자동완성, Tab키를 두 번 연속 누르면 suggest를 보여준다.

참고

25Python 기초 교육

# .pystartup# export PYTHONSTARTUP=~/.pystartup

import atexitimport osimport readlineimport rlcompleter

readline.parse_and_bind('tab: complete')

historyPath = os.path.expanduser("~/.pyhistory")

def save_history(historyPath=historyPath):import readlinereadline.write_history_file(historyPath)

if os.path.exists(historyPath):readline.read_history_file(historyPath)

atexit.register(save_history)del os, atexit, readline, rlcompleter, save_history, historyPath

• $PYTHONSTARTUP 파일 예제

참고

26Python 기초 교육

파이썬 실행 방법

• 대화식 명령행

• 모듈 파일 실행

• 유닉스 스타일의 스크립트 파일

• 다른 시스템에 내장된 형태

28Python 기초 교육

파이썬 실행 방법

• 대화식 명령행

Windows

Linux

29Python 기초 교육

파이썬 실행 방법

• 모듈 파일

# spam.pyimport sysprint sys.argv

Windows

Linux

30Python 기초 교육

파이썬 실행 방법

• 유닉스 스타일에서 스크립트 파일의 실행

31Python 기초 교육

파이썬 실행 방법

• 임베디드 코드와 객체

#include <Python.h>. . .Py_Initialize();PyRun_SimpleString(“x = brave + sir + robin”);

예) C언어에서 파이썬 인터프리터를 실행

32Python 기초 교육

모듈 파일

• 모듈 파일은 운영체제 쉘 명령어로 수행할 수도 있고 파이썬의 대화식 명령행에서도 수행할 수 있다.

• 파이썬 명령행에서는 모듈을 가져오기 위해 import 명령을 사용한다.• 모듈 파일의 파일명은 .py 확장자를 갖는다.

$ python>>> import myfile>>> print myfile.stringLife is very short! Use Python!>>>

string = "Life is very short! Use Python!"

myfile.py

$ python>>> from myfile import string>>> print stringLife is very short! Use Python!>>>

import문으로 모듈 전체를 가져오는 방법

from을 이용하여 모듈에서 이름을 이름을 읽어오는 방법

주의!!- 파이썬은 모듈 파일을 처음 가져올 때 그 안의 모든 코드를 처음부터 끝까지 수행한다.- 그러나 같은 세션에서는 또 다시 모듈 파일을 가져와도 파이썬은 이를 재수행하지는 않는다.

33Python 기초 교육

모듈 파일

• 파일의 코드를 재수행하려면 파이썬의 reload 함수를 사용한다.

$ python>>> import myfile>>> print myfile.stringLife is very short! Use Python!>>>

string = "Life is very short! Use Python!"

myfile.py

편집기를 이용하여 myfile.py를 변경한다.

>>> import myfile>>> print myfile.stringLife is very short! Use Python!>>> reload(myfile)<module 'myfile' from 'myfile.py'>>>> print myfile.stringPython is Simple.>>>

34Python 기초 교육

네임스페이스

• 내장 함수인 dir을 이용하여 대화식 프로그램에서 정의된 이름을 추적한다.• 인수 없이 dir 함수를 호출하면 네임스페이스(namespace)에 정의된 이름

이 있는 리스트를 얻는다.

>>> x = 1>>> y = 'hello'>>> dir()['__builtins__', '__doc__', '__name__', 'x', 'y']

주의!!- dir()은 함수 호출이다. 함수명 뒤에 괄호를 사용하여 호출한다는 것을 주의 하자.- dir이 호출될 때, 일부 이름은 ‘공짜’로 얻는다. 이것은 내장된 이름으로 파이썬에서 미리 정의되어 있다.

35Python 기초 교육

네임스페이스• 참고로...

– __name__은 모듈의 파일명이다.– __builtins__는 파이썬에 내장된 모든 이름을 갖는 모듈이다.

$ python>>> dir()['__builtins__', '__doc__', '__name__']>>> __name__'__main__'>>> __builtins__<module '__builtin__' (built-in)>>>> dir(__builtins__)['ArithmeticError', 'AssertionError', 'AttributeError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'IOError', 'ImportError', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'OverflowWarning', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', '__name__', 'abs', 'apply', 'basestring', 'bool', 'buffer', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min', 'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'round', 'setattr', 'slice', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']

36Python 기초 교육

네임스페이스

• 모듈을 인수로 dir을 호출하면, 그 모듈 내부에 정의된 이름을 얻게 된다.$ cat threenames.pya = 'a'b = 'b'c = 'c'

$ python>>> import threenames>>> dir(threenames)['__builtins__', '__doc__', '__file__', '__name__', 'a', 'b', 'c']>>>

37Python 기초 교육

파이썬 환경설정

• 환경변수– PYTHONPATH: 파이썬 모듈 검색 경로

– PYTHONSTARTUP: 파이썬 대화식 인터프리터 시작 파일 경로

– TCL_LIBRARY, TK_LIBRARY: GUI 확장 변수(Tkinter)• 파이썬에서 모듈을 가져올 때 모듈을 찾는 순서

– 현재 디렉토리(.)– PYTHONPATH에 정의된 순서

– 파이썬 소스 라이브러리가 설치되어 있는 경로([설치경로]/lib/python)

참고

38Python 기초 교육

파이썬 환경설정

• 윈도우에서 실행 방법– runpy.cmd 파일을 다음과 같이 만들고 클릭하여 실행

@PATH c:\python24;%PATH%@set PYTHONPATH=.;C:\python24\lib;@python

참고

39Python 기초 교육

GUI 테스트

• Tkinter를 이용한 GUI 테스트

# gui.pyfrom Tkinter import *w = Button(text='Hello', command='exit')w.pack()w.mainloop()

# python gui.py Traceback (most recent call last):File "gui.py", line 2, in ?

from Tkinter import *File "/usr/local/python2.4.2/lib/python2.4/lib-tk/Tkinter.py", line 38, in ?

import _tkinter # If this fails your Python may not be configured for Tk

참고

40Python 기초 교육

파이썬의 자료형

• 수치형

– 3.1415, 1234, 999L, 3+4j• 문자열: ' ' 또는 " " 로 감싸준다

– 'spam' "guido's"• 리스트

– [] [1, 2, 3] [1, [2, 'three'], 4]• 사전

– {} {'food': 'spam', 'taste': 'yum'}• 튜플

– (1, 'spam', 4, 'U')• 파일

– text = open('eggs', 'r').read()

42Python 기초 교육

연산자연산자 설명

x or y 논리적 or (y는 x가 거짓일 때만 평가된다)

lambda args: expression 이름 없는 함수

x and y 논리적 and (y는 x가 참일 때만 평가된다)

not x 논리 부정

<, <=, >, >=, ==, <>, != 비교 연산자

is, is not 동일성 검사

in, not in 시퀀스 멤버 검사

x | y 비트단위 or

x ^ y 비트단위 xor

x & y 비트단위 and

x << y, x >> y y비트 만큼 x를 왼쪽, 오른쪽으로 쉬프트 이동

x + y, x – y 더하기/붙이기, 빼기

x * y, x / y, x % y 곱하기/반복, 나누기, 나머지/포맷

-x, +x, --x 단항 연산자 부호 전환, 동일 값, 1의 보수

x[i], x[i:j], x.y, x(...) 인덱싱, 슬라이싱, 자격부여, 함수 호출

(...), [...], {...}, ‘...’ 튜플(tuple), 리스트(list), 사전(dictionary), 문자열로 변환43Python 기초 교육

수치형

• 수치형

– 정수: 1234, -24, 0– long형 정수(무제한): 999999999999999L– 부동소수점(C언어에서 double): 1.23, 3.14e-10, 4E210– 8진수: 0177– 16진수: 0x9ff– 복소수: 3+4j, 3.0+4.0j, 3J

(수치연산을 위한 내장도구)– 산술연산자: +, *, >>, ** 등– 내장 수학함수: pow, abs 등– 유틸리티 모듈: rand, math 등

44Python 기초 교육

수치형

>>> 999999999999999999*9999999999999999*999999999999999999999999999999999989890000000000000011009999999999999999L>>> 3.14e-103.14e-10>>> 3.14e-1003.1399999999999999e-100>>> 3.14e-10000.0>>> 4E1000inf>>> 1.234567890123456789012345678901.2345678901234567>>> 0177127>>> 0x9ff2559>>> 3j*3j(-9+0j)>>>

수치형

45Python 기초 교육

수치형

>>> a = 3>>> b = 4>>> b / 2 + a5>>> 2.0+a5.0>>> b / (2.0 + a)0.80000000000000004

기본연산자

>>> x = 1>>> x << 2 # 왼쪽 쉬프트4>>> x | 2 # 비트 단위 OR x=>0001, 2=>00103>>> x & 3 # 비트단위 AND x=>0001, 3=>00111

비트 연산자

46Python 기초 교육

수치형

>>> import math>>> math.pi3.1415926535897931>>> abs(-123456789) # abs 는 import 없이도 사용할 수 있다. __builtins__포함123456789>>> 2**416>>> pow(2,4)16

수치연산 도구

>>> x = 1>>> x << 2 # 왼쪽 쉬프트4>>> x | 2 # 비트 단위 OR x=>0001, 2=>00103>>> x & 3 # 비트단위 AND x=>0001, 3=>00111

비트 연산자

47Python 기초 교육

문자열

• 문자열– 문자의 순서를 갖는 집합 (기호, 단어, 메모리로 적제된 텍스트 파일 내

용 등)– 파이썬에는 C언어와는 다르게 단 한 개의 문자를 나타내는 char형이 없

다.– 정확하게 말하면 파이썬 문자열은 변경이 불가능한 시퀀스(immutable

sequence)형으로 분류된다. 일반적인 시퀀스 연산을 하지만 값을 변경할 수 없다

s1 = '' # 빈 문자열s2 = "spam's" 또는 'spam"s' # 이중 인용부호block = """........""" # 삼중 인용블럭s1+s2 # 연결s2*3 # 반복s2[i] # 인덱스s2[i:j] # 슬라이스len(s2) # 길이"%s님 안녕하세요" % "홍길동" # 문자열 포맷팅for x in s2 # 반복'm' in s2 # 멤버쉽

48Python 기초 교육

문자열

>>> s = 'abcdefghijklm'>>> s2 = "spam's" 또는 'spam\'s'>>> s2"spam's">>> block = """ hello... 1234567890... spam... """>>> block' hello\n1234567890\nspam\n'>>> s2+s2"spam'sspam's"

>>> s*3'abcdefghijklmnabcdefghijklmnabcdefghijklmn'>>> s[5]'f'>>> s[2:7]'cdefg'>>> len(s)14

문자열 연산 예제

>>> for x in s2: print x...spam's>>> 'm' in sTrue>>> 'ij' in sTrue

49Python 기초 교육

문자열문자열 슬라이싱

s="abcde"0 1 2 3 4

-5 -4 -3 -2 -1

>>> s = "abcde">>> s[0:5]'abcde'>>> len(s)5>>> s[0]'a'>>> s[-1]'e'>>> s[-2]'d'>>> s[1:]'bcde'>>> s[1:3]'bc'>>> s[:-1]'abcd'

5

인덱싱•오프셋으로 컴포넌트를 읽어낸다.•음수 첨자는 끝자부터 센다 (문자열 길이를 더한 위치이다)

S[-2]는 S[len(s)-2] 와 같다.슬라이싱•시퀀스의 연속적인 영역을 추출한다.•생략되면 시작 값은 0이고 끝 값은 시퀀스의 길이이다

50Python 기초 교육

문자열문자열 변경

>>> s = 'spam'>>> s[0] = 'x' # 에러를 발생Traceback (most recent call last):File "<stdin>", line 1, in ?

TypeError: object does not support item assignment>>> s = 'x' + s[1:]>>> s'xpam'

>>> "That is %d %s bird!" % (1, 'dead')'That is 1 dead bird!'

>>> "%d %s %d you" % (1, 'spam', 4)'1 spam 4 you'

>>> "%s -- %s -- %s" % (42, 3.14159, [1,2,3]) # %s 는 모든 객체를 문자열로 변환'42 -- 3.14159 -- [1, 2, 3]'

문자열 포맷팅

51Python 기초 교육

문자열

• 문자열 포맷 코드– %s 문자열

– %c 문자

– %d 10진수(정수)– %i 정수

– %u 부호 없는 정수(정수)– %o 8진수

– %x,%X 16진수

– %e, %E, %f, %g, %G 부동 소수점 포맷

– %% 문자%

52Python 기초 교육

문자열

• 공통 문자열 도구

>>> import string # 표준 유틸리티 모듈

>>> s = 'spammify'

>>> string.upper(s) # 대문자로 변환

'SPAMMIFY'

>>> string.find(s, 'mm') # 부문자열 'mm'의 위치

3

>>> string.atoi('42'), "%d" % 42 # 문자열, 숫자의 상호 변환

(42, '42')

>>> string.join(string.split(s, 'mm'), 'xx')

'spaxxify'

53Python 기초 교육

문자열

• 역슬래시 문자– \newline 무시(연속)– \\ 역슬래시(한개의 '\' 문자)– \' 단일 인용 부호

– \" 이중 인용 부호

– \b 역스페이스

– \000 널(Null, 문자열 끝이 아님)– \n 개행

– \t 탭– \r carriage return– \f form feed– \0XX 8진수

– \xXX 16진수

54Python 기초 교육

리스트(list)• 리스트

– 객체 자료의 순서를 갖는 집합

– 문자열과는 달리 수치형, 문자열형, 리스트와 같은 어떤 종류의 객체도포함 할 수 있다.

– 가변 길이, 이질적인 자료를 포함, 임의로 내포가능

– 객체 레퍼런스의 배열

– 명시적으로 복사를 요구하지 않는다면 객체의 복사본을 저장하지 않는다. (C언어의 포인터 개념)

55Python 기초 교육

리스트a1 = []

a2 = [0,1,2,3]

a3=['abc',['def','ghi']] # 리스트가 리스트 안에 포함됨

a2[2], a3[1][2] # 인덱스

a2[1:3] # 슬라이스

len(a2) # 길이

a2+a3 # 연결

a2*3 # 반복

for x in a2 # 루프반복

3 in a2 # 멤버쉽

a2.append(4) # append() 메소드

a2.sort() # 정렬

a2.index(1) # 검색

a2.reverse() # 순서 바꾸기

del a2(k) # 슬라이스

a2[i:j] = [] # 줄이기

a2[i] = 1 # 인덱스를 이용한 할당 (문자열에서는 불가능)

a2[i:j] = [4,5,6] # 슬라이스 할당 (문자열에서는 불가능)

range(4), xrange(0,4) # 정수의 리스트/튜플 만들기

56Python 기초 교육

리스트>>> a = [0, 1, 2, 'abc', ['d','e','f','g']]>>> a[0, 1, 2, 'abc', ['d', 'e', 'f', 'g']]>>> a[3]'abc'>>> a[4]['d', 'e', 'f', 'g']>>> a[4][1]'e'>>> a[1:3][1, 2]>>> len(a)5>>> a + a[4][0, 1, 2, 'abc', ['d', 'e', 'f', 'g'], 'd', 'e', 'f', 'g']

>>> del a[2]>>> a[50, 4, 2, 1, 0]>>> a[1:2] = [6,7]>>> a[50, 6, 7, 2, 1, 0]>>> a.sort()>>> a[0, 1, 2, 6, 7, 50]

>>> 3 in aFalse>>> a.append(50)>>> a[0, 1, 2, 'abc', ['d', 'e', 'f', 'g'], 50]>>> a.index(50)5>>> a.reverse()>>> a[50, ['d', 'e', 'f', 'g'], 'abc', 2, 1, 0]>>> a[1] = 4>>> a[50, 4, 'abc', 2, 1, 0]

57Python 기초 교육

사전(dictionary)• 사전

– 순서를 갖지 않는 객체의 집합

– 사전은 저장과 검색이 오프셋이 아니라 키(key)에 의해서 이루어 진다. 사전을 때로는 연관 배열(associative array) 또는 해시(hash)라고도한다.

– 사전에 저장된 항목은 특별한 순서를 유지하지 않는다. 빠른 검색을 위해 순서를 무작위화한다.

– 가변 길이, 이질적인 자료를 포함할 수 있으며, 내포가능 하다.

– 사전에서 시퀀스 연산은 할 수 없다.– 키는 항상 문자열일 필요는 없다.

58Python 기초 교육

사전d1 = {} # 빈 사전

d2 = {'spam':2, 'eggs':3} # 두 개의 항목 사전

d3 = {'food':{'ham':1, 'egg':2} # 내포

d2['eggs'], d3['food']['ham'] # 키에 의한 인덱싱

d2.has_key('eggs') # 멤버쉽 테스트

d2.keys() # 키 리스트

d2.values() # 값 리스트

len(d1) # 길이 (엔트리 숫자)

d2[key] = new # 추가/변경

del d2[key] # 삭제

59Python 기초 교육

사전>>> d1 = {}>>> d2 = {'spam':2, 'eggs':3}>>> d2{'eggs': 3, 'spam': 2}>>> d1{}>>> d3 = {'food':{'ham':1, 'egg':2}}>>> d2['eggs'], d3['food']['ham'](3, 1)>>> d2.has_key('eggs')True>>> d2.keys()['eggs', 'spam']>>> d2.values()[3, 2]>>> len(d2)2>>> d2['milk'] = 1>>> d2{'eggs': 3, 'milk': 1, 'spam': 2}>>> del d2['milk']>>> d2{'eggs': 3, 'spam': 2}

60Python 기초 교육

예제table = {'Python' : 'Guido van Rossum',

'Perl' : 'Larry Wall','Tcl' : 'John Ousterhout' }

language = 'Python'creator = table[language]print creatorfor lang in table.keys():

print "%s\t%s" % (lang, table[lang])

>>> table = {'Python' : 'Guido van Rossum',... 'Perl' : 'Larry Wall',... 'Tcl' : 'John Ousterhout' }>>> language = 'Python'>>> creator = table[language]>>> print creatorGuido van Rossum>>> for lang in table.keys():... print "%s\t%s" % (lang, table[lang])...Python Guido van RossumTcl John OusterhoutPerl Larry Wall

61Python 기초 교육

튜플(tuple)• 튜플

– 객체의 그룹을 형성하며 리스트와 동일하게 동작하지만, 내용을 바꿀 수는 없다.

– 일반괄호(())안에 항목을 기술한다.– 순서를 갖는 객체의 집합이다. 오프셋으로 참조된다.– 리스트처럼 값을 변경할 수 없다.– 고정된 길이이고, 이질적인 자료를 포함하며 내포될 수 있다.– 튜플은 리스트나 사전처럼 메소드는 지원하지 않는다.

• 리스트가 있는데 왜 튜플을 사용할까?– 튜플의 변경 불가능성 때문에 프로그램의 다른 부분에서 다른 레퍼런스에 의해서 변경되지 않는 것을 확신할 수 있기 때문이다.

62Python 기초 교육

튜플() # 빈 튜플

t1 = (0,) # 한 개의 항목을 가진 튜플

t2 = (0, 1, 2, 3) # 네 개의 항목을 가진 튜플

t2 = 0, 1, 2, 3 # 위와 같음

t3 = ('abc', ('def', 'ghi')) # 내포된 튜플

t2[2], t3[1][0] # 인덱스

t2[1,3] # 슬라이스

len(t1) # 길이

t1 + t2 # 연결

t2 * 3 # 반복

for x in t2 # 루프반복

3 in t2 # 멤버 쉽

63Python 기초 교육

튜플>>> t1 = (0)>>> t10>>> t1 = (0,)>>> t1(0,)>>> t2 = 0, 1, 2, 3>>> t2(0, 1, 2, 3)>>> t3 = ('abc', ('def', 'ghi'))>>> t3('abc', ('def', 'ghi'))>>> t2[2], t3[1][0](2, 'def')>>> t2[1:3](1, 2)>>> len(t1)1>>> t1 + t2(0, 0, 1, 2, 3)>>> t2*3(0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3)>>> for x in t2 : print x,...0 1 2 3>>> 3 in t2True

64Python 기초 교육

QUIZ

>>> a = [1,2,3]>>> b = a>>> a.append(4)>>> b ?

>>> a = (1,2,3)>>> b = a>>> a = (4,5)>>> b ?

>>> a = {1:2}>>> b = a>>> a[1] = 3>>> b ?

리스트

튜플

사전

>>> a = [1,2,3]>>> b = a>>> a = [4,5,6]>>> b ?

>>> a = {1:2}>>> b = a>>> a = {}>>> b ?

>>> a = (1,2,3)>>> a(0) = -1???

65Python 기초 교육

빠지기 쉬운 함정

• 치환문은 복사가 아니라 레퍼런스를 생성한다.>>> X = [1,2,3]>>> L = ['a', X, 'c']>>> D = {'x': X, 'y': 2}

>>> X[1] = 'surprise'>>> L['a', [1, 'surprise', 3], 'c']>>> D{'y': 2, 'x': [1, 'surprise', 3]}

• 비교(==, is)– 내포 객체가 있을 경우에는 자동적으로 자료구조를 다니면서 재귀적

(recursive)으로 비교한다.>>> L1 = [1, ('a', 3)]>>> L2 = [1, ('a', 3)]>>> L1 == L2 # 같은 값인가 ??True>>> L1 is L2 # 같은 객체인가 ??False

1 2 3X

a cL

x: y:2D

공유객체

66Python 기초 교육

빠지기 쉬운 함정• 명시적으로 공유 레퍼런스를 복사함으로 공유객체를 피할 수 있다.

– 리스트에서는 슬라이스를 이용하여 객체를 복사할 수 있다.>>> a = [1,2,3]>>> b = a[:] # a의 객체를 복사>>> a[1] = 100>>> b[1, 2, 3]>>> a[1, 100, 3]

• 시퀀스의 반복>>> L = [4,5,6]>>> X=L*4 # [4,5,6] + [4,5,6] + ...>>> Y=[L]*4 # [L] + [L] + ...>>> X[4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6]>>> Y[[4, 5, 6], [4, 5, 6], [4, 5, 6], [4, 5, 6]]

>>> L[1] = 0>>> X[4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6]>>> Y[[4, 0, 6], [4, 0, 6], [4, 0, 6], [4, 0, 6]]

반복, 연결, 슬라이싱 복사에서는 피연

산자 객체의 최상위 수준만을 복사한다.

67Python 기초 교육

빠지기 쉬운 함정• 순환적 자료구조는 출력이 안 된다.

– 되도록이면 사용하지 말도록 한다.>>> L = ['hi']>>> L.append(L) # 같은 객체로 레퍼런스를 추가한다.>>> L['hi', [...]] # 1.5.1 이전에는 무한루프였다 (Ctrl-C로 중단시켜야 했다.)

68Python 기초 교육

파일

• 파일– 파일은 파이썬에 내장된 객체이다.– 내장 open 함수를 이용하여 파일 객체를 생성하고 파일 객체 메소드를

호출함으로써 관련된 파일내의 데이터를 읽거나 쓸 수 있다.– C언어의 stdio 파일 시스템의 레퍼(wrapper)역할을 한다.

output = open('/tmp/spam', 'w') # 출력 파일 생성input = open('data', 'r') # 입력 파일 열기s = input.read() # 전체 파일을 단일 문자열로 읽기s = input.read(N) # N 바이트 읽기s = input.readline() # 다음 행 읽기l = input.readlines() # 전체 파일을 행 문자열의 리스트로 읽음output.write(S) # 파일에 문자열 S를 쓰기output.writelines(L) # 파일에 리스트 L의 모든 행 문자열을 쓰기output.close() # 직접 닫기 (직접 닫지 않으면 자동으로 처리됨)

69Python 기초 교육

파일output = open('/tmp/spam', 'w') # 출력 파일 생성input = open('data', 'r') # 입력 파일 열기s = input.read() # 전체 파일을 단일 문자열로 읽기s = input.read(N) # N 바이트 읽기s = input.readline() # 다음 행 읽기l = input.readlines() # 전체 파일을 행 문자열의 리스트로 읽음output.write(S) # 파일에 문자열 S를 쓰기output.writelines(L) # 파일에 리스트 L의 모든 행 문자열을 쓰기output.close() # 직접 닫기 (직접 닫지 않으면 자동으로 처리됨)

# filetest.pymyfile = open('myfile', 'w')myfile.write('hello text file\n')myfile.close()

myfile = open('myfile', 'r')l = myfile.readline()print ll = myfile.readline()print l

70Python 기초 교육

연습문제

• 리스트에서 한계영역 밖으로 첨자를 사용했을 때 무슨 일이 일어나는가?– L=[0,1,2,3] L[4]

• 한계영역 밖으로의 슬라싱은? L[-1000:1000]• 슬라이싱에서 하한 값이 상한 값보다 크다면? L[3:1]• 객체의 속성을 리스트화 시키는 dir()

– dir([])– dir({})– dir('')

71Python 기초 교육

파이썬 문(文)• 문(文, statement) 이란?

– 프로그램이 할 일을 파이썬에 알려주기 위해 서술하는 것

• 프로그램의 구성

– 프로그램(program)은 모듈(module)로 이루어져 있다.– 모듈은 문(statement)로 이루어져 있다.– 문은 객체(object)를 생성하고 처리한다.

• 파이썬 문의 종류

치환문 레퍼런스 생성 S,J,L='abc',123,[]

호출 함수 실행 stdout.write('spam\n')

출력 객체 출력 print "Hi", name

if/elif/else 선택적 수행 if ‘py’ in text: print text

for/else 시퀀스 반복 for x in list: print x

while/else 일반적 루프 while True: print 'hello'

pass 아무것도 하지 않음 while 1: pass

break, continue 루프 점프73Python 기초 교육

파이썬 문(文)• 파이썬 문의 종류 (계속)

try/except/finally 예외 검출 try: action() except: print ‘action err’

raise 예외 발생 raise endSearch, location

import, from 모듈 접근 import sys; from sys import stdin

def, return 함수 정의 def f(a,b,c=1,*d): return a+b+c+d[0]

class 객체 정의 class subclass: staticData=[]

global 네임스페이스 def func(): global x, y; x = ‘new’

del 객체 삭제 del data[k]; del data[i:j]; del obj.attr

exec 코드 문자열 수행 exec ‘import’ + modName

assert 디버깅 검사 assert X > Y

74Python 기초 교육

파이썬의 문법 규칙

• 문은 순차적으로 수행된다.– 프로그램을 수행되는 순서를 제어하기 위해 제어 흐름문

(control-flow statement)를 사용한다. (if, for, while, …)• 블록과 문의 경계는 자동으로 검출된다.

– 코드 블록 주위에 {}나 begin/end와같은 구분자가 없다.– 헤더 아래의 들여쓰기를 이용하여 내포된 블록을 구분한다.– 파이썬문은 C언어처럼 세미콜론으로 끝나지 않는다.

• 복합문은 헤더, ‘:’, 내포문 으로 구성된다.– 문이 하나인 복합문에서 몸체를 헤더로 옮길 수 있다.

• 공백이나 주석은 무시된다.– 주석은 ‘#’문자로 시작하여 그 행의 끝까지이다.# commentfor name in people:if name in myfriends: # commentprint 'Hi! %s', name

75Python 기초 교육

파이썬의 문법 규칙

• 문이 한 행에 들어가지 못 할 때– (), {}, [] 괄호를 사용할 경우에는 문이 길더라도 여러 행에쓸 수 있다.

– 역슬래시로 문이 끝나면 행은 연속된다.– 원한다면 문을 세미콜론으로 끝마칠 수도 있다.

L = ['Good','Bad','Ugly']

if a == b and c == d and \d == e and f == g:print 'bravo'

if ( a == b and c == d and d == e and f == g):print 'bravo'

x = 1; y = 2; print xif wantPrint: print ‘hello’

76Python 기초 교육

치환문(assignment)• 치환문은 객체의 레퍼런스를 생성한다.• 치환되지 않은 이름은 에러를 발생한다.

>>> print undefined_variableTraceback (most recent call last):File "<stdin>", line 1, in ?

NameError: name 'undefined_variable' is not defined• 잠재적(implicit) 치환: import, from, def, class, for, 함수인수 등• 튜플과 리스트 언패킹(unpacking) 치환

– 튜플이나리스트를 =의 왼쪽에 사용할 경우– 오른쪽객체를 왼쪽의 이름과 짝을 맞추어 준다a, b = b, a # 튜플 치환을 이용한 값의 교환

• 복수 타켓 치환spam = ham = ‘lunch’ 은 ham = ‘lunch’ ; spam = ham 과 같다.

77Python 기초 교육

변수명의 규칙

• 변수명은 언더스코어, 문자, 숫자로 구성되며 언더스코어 또는 문자로 시작한다.– _spam, spam, Spam_1 은 올바르다– 1_spam, spam$, sp@am 등은 올바르지 않다

• 변수명은 대소문자를 구분한다.– SPAM은 spam과 같지 않다.

• 예약어는 사용할 수 없다.– and, assert, break, class, continue, def, del, elif, else, except,

exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while

78Python 기초 교육

표현식(expression)• 표현식이 문으로 사용되는 경우(표현식 문)

– 함수와 메소드 호출을 위해– 대화식 프롬프트에서 값을 출력하기 위해

• 일반적인 파이썬 표현식 문– spam(egg, ham) 함수호출– spam.ham(eggs) 메소드 호출– spam 대화식 출력– spam < ham and ham != eggs 복합식– spam < ham < egg 영역 테스트

• 표현식이 문으로 표현되기는 하지만 문은 표현식이 될 수 없다.– 예를들어 C언어와는 달리 파이썬은 치환문(=)이다른 표현식 안에 포함되는것을 허용치 않는다. 비교테스트(==)를해야 할 경우에 =를 입력하여 변수를 잘못 변경하는 일은 파이썬에서 일어날 수 없다.

– a = 1; b = 1; if a=b: print 'equal' # 오류79Python 기초 교육

출력(print)• print 문은 객체의 문자적 표현을 ‘표준 출력 스트림’으로 보낸다.

– 콤마로 구분된 항목 사이에 공백을 넣고, 출력행 마지막에 라인피드를 추가한다.print spam, ham # sys.stdout 으로 출력하고 사이에 공백을 추가print spam, ham, # 위와 같으나 마지막에 줄 바꾸기는 없다.>>> print 'hello world'hello world>>> import sys>>> sys.stdout.write('hello world\ n')hello world

• print 문은 텍스트를 단순히 sys.stdout.write메소드로보낸다.class FileFaker:

def write(self, string):# 문자열을 이용하여 무언가를 한다.

import syssys.stdout = FileFaker() # sys.stdout 객체를 바꿈print someObjects # FileFaker 클래스의 write 메소드로 보낸다.

80Python 기초 교육

if 테스트

• if 문은 대부분의 언어와 같다. 구문은 다음과 같다.

if <test1>:<statement1>

elif <test2>:<statement2>

else:<statement>

#!/usr/bin/python# Filename : if.pynumber = 23guess = int(raw_input('Enter an integer : '))if guess == number:

print 'Congratulations, you guessed it.'print "(but you don't win any prizes!)"

elif guess < number:print 'No, it is a little higher than that.'

else:print 'No, it is a little lower than that.'

print 'Done'

• C언어나파스칼에서 사용되는 switch, case 문이 파이썬에는없다. if/elif를연속해서사용하거나, 사전 혹은 리스트 검색을 이용한다.

81Python 기초 교육

while 루프

• 상단부분의 테스트가 참인 동안 문의 블록을 반복적으로실행한다.

while <test>:<statement1>

else:<statement2>

>>> while 1:... print 'Type Ctrl-C to stop me!‘

x = 'spam'while x:print x,x = x[1:] # x의 첫 문자를 버린다.

a = 0while a < 10:print a,a += 1

else: print 'exit'

82Python 기초 교육

break, continue, pass, 루프 else• break: 가장 가까운 루프를 벗어난다.• continue: 가장 가까운 루프의 최상단으로 간다.• pass: 아무 일도 하지 않는다. 자리를 채우기 위한 빈 문(empty statement)• 루프 else: 루프가 정상적으로 끝났을 때만 수행한다.

while <test>:<statements>if <test>: break # 루프를 빠져나가며, else를 건너뛴다if <test>: continue # 루프의 최상위로 간다

else: # break를 수행하지 않았을 때만 해당된다.<statements>

def do_nothing():pass

83Python 기초 교육

for 루프

• 가장기본적인 시퀀스 반복문이다.– 문자열, 리스트, 튜플, 클래스 객체에 적용이 가능하다.

for <target> in <object>: # 객체의 각 항목을 target으로 치환<statements>

else: # for문 안에서 break문을 수행하지 않았다면<statements>

for x in ['spam', 'eggs', 'ham']:print x,

sum = 0for x in [1,2,3,4]:sum = sum + x

S = 'lumberjack'for x in S: print x,

T = ('and', "I'm", 'okay')for x in T: print x,

T = [(1,2),(3,4),(5,6)]for (a,b) in T:

print a, b

84Python 기초 교육

for 루프

set = ["aaa", 111, (4, 5), 2.01 ]testitems = [(4,5), 3.14]for key in testitems:for item in set:if key == item:print key, 'was found'break

else:print key, 'not found'

(4, 5) was found3.14 not found

set = ["aaa", 111, (4, 5), 2.01 ]testitems = [(4,5), 3.14]for key in testitems:if key in set:print key, 'was found'

else:print key, 'not found'

seq1 = "spam"seq2 = "scam"common = []for x in seq1:if x in seq2:common.append(x)

print common

set 안에 testitems안의 아이템이 들어 있는지 하나씩 검사한다.

['s', 'a', 'm']

문자열에서 공통적인 문자만 뽑아 리스트로 만든다.

85Python 기초 교육

for 루프

file = open(filename, 'r')while 1:line = file.readline()if not line: breakprint line

첫 번째 줄

두 번째 줄

세 번째 줄

range 내장 함수는 연속적인 정수의 리스트를 만든다

첫 번째 줄두 번째 줄세 번째 줄

filename.txt

file = open(filename, 'r')lines = file.readlines()for line in lines:print line

>>> range(5), range(2,5), range(0, 10, 2)([0, 1, 2, 3, 4], [2, 3, 4], [0, 2, 4, 6, 8])

for i in range(3): print i, 'pythons'0 pythons1 pythons2 pythons

86Python 기초 교육

함수의 기초

• 왜 함수를 사용하는가?– 코드의 재사용: 반복되어 사용되는 코드 블럭을 함수로 정의하여 반복 호출한다.

– 절차적 분해: 전체를 한꺼번에 구현하기 보다는 독립적인 작은 단위로 나누어 구현하는 것이 더 쉽다. 함수는 큰 프로그래밍을 할 수 있도록 도와 준다.

• 함수의 기초– 함수의 선언은 def 로 시작한다: 함수 객체를 생성해서 함수명에 할당한다.– return은 호출자(caller)에게 객체의 결과를 되돌려 준다.– global은 모듈 수준의 변수를 함수 안에서 치환할 때 사용한다.– 인수는 치환(레퍼런스)에 의해서 함수로 전달된다. 함수 호출자와 함수는 같은 객체를 레퍼런스를 통해 공유한다.

– 인수, 리턴 자료형, 변수는 선언되지 않는다.– return 문이 없는 함수는 자동적으로 None 객체를 리턴한다.– 함수안에서 치환된 이름은 함수의 네임스페이스에만 연결된다.

def <name> (arg1, arg2, ..., argN):<statements>return <value>

88Python 기초 교육

함수의 기초

• 예제 >>> def times(x, y):... return x * y...>>> times(2,4)8>>> times('Ni', 4) # 함수는 형이 정해져 있지 않다.'NiNiNiNi'

def intersect(seq1, seq2):common = []for x in seq1: # seq1에 대하여if x in seq2: # seq1와 seq2에서 변수common.append(x)

return common

s1 = 'spam'; s2 = 'scanm'; print intersect(s1, s2) # 문자열print intersect([1,2,3],(1,4)) # 혼합 자료형['s', 'a', 'm'][1]

89Python 기초 교육

함수의 기초

• 함수의 영역 규칙: 지역->전역->내장– 지역(함수): def 함수 안에서 치환된 이름– 전역(모듈): 모듈의 최상위 수준에서 치환된 이름, 함수안에서 global 로정의된이름

– 내장(파이썬): 미리 정의된 이름. open, len 등

X = 99 # X는 모듈 안에서 치환됨: 전역def func(Y): # Y와 Z는 함수 안에서 치환됨: 지역# 지역 영역Z = X + Y # X는 치환되지 않았으므로 전역return Z

func(1) # 결과=100

y, z = 1, 2def all_global():global x # 치환될 변수를 global 로 선언x = y + z

all_global() # 함수 호출print x # 결과=3

90Python 기초 교육

함수의 기초

• 인수 전달– 인수는객체를 지역 이름으로치환하여 전달한다.– 함수내에 있는 인수명으로 치환하는것은 호출자에게영향이 없다. – 변경가능한 객체 인수를 함수 안에서 변경하면호출자에게 영향을 준다.

def changer(x, y):x = 2y[0] = 'spam' # 호출자에게 영향을 준다.

# 이것을 피하려면 y=y[:]로 복사해서# 사용해야 한다.

X = 1L = [1, 2]changer(X, L)print X, L # X는 변화가 없지만,

# L은 다른 값이다.

1 ['spam', 2]

1

[1,2]

X

L

x

y

이름 객체

호출자

함수

변경불가능

변경가능

• 변경이 불가능한 인수는 C언어의 '값에 의한' 모드와 유사 (call by value)• 변경이 가능한 인수는 C 언어의 '포인터에 의한' 모드와 유사 (call by reference)

91Python 기초 교육

함수의 기초

• return문은 어떤 종류의 객체도 돌려줄 수 있으며, 여러 값을 튜플에 묶어서돌려줄수도 있다.

def multiple(x, y):x = 2y = [3, 4]return x, y # 새로운 값을 튜플로 리턴

# return (x, y) 와 같다.

X = 1L = [1, 2]X, L = multiple(X, L) # 또는 (X, L) = multiple(X, L)print X, L

92Python 기초 교육

함수의 기초

• 인수매칭 방법들

func(value1, value2, ..., valueN)def func(name1, name2, ..., nameN)

– 왼쪽에서 오른쪽으로 하나씩 대응 (일반적인 방법)

– 기본값 지정하기: 전달되지 않은 인수의 값을 지정한다

– 나머지 인수 모음

– 키워드 인수: 인수명으로 매칭하기func(name=value)def func(name)

func()def func(name=value)

def func(*name) # 나머지 위치적 인수를 튜플로 매치def func(**name) # 나머지 키워드 인수를 사전으로 매치

• 규칙– 함수를 호출할 경우 키워드 인수는 모든 비 키워드 인수 이후에 나와야 한다.

ex) func(1, 2, a=3, 4, b=5) 은 오류– 함수 헤더에 *name은 일반 인수와 기본 인수 뒤에 나와야 하며, **name은 마지막에 나와야 한다.

93Python 기초 교육

함수의 기초

• 인수매칭 방법들: 위치, 기본값, 키워드def func(spam, eggs, toast=0, ham=0):print (spam, eggs, toast, ham)

func(1,2) # 3번째, 4번째는 기본값으로 지정된다.func(1, ham=1, eggs=0) # 1번째는 위치로, 2,3번째는 키워드로 매칭func(spam=1, eggs=0) # 1,2번째가 키워드로 매칭func(toast=1, eggs=2, spam=3) # 1,2,3번째가 키워드로 매칭func(1, 2, 3, 4) # 모두 다 위치순서로 매칭

# inter.pydef intersect(*args): # 인수로 전달된 시퀀스들의 교집합 리스트를 구함res = []for x in args[0]: # 첫 번째 시퀀스에 대해for other in args[1:]: # 두 번째 이후 시퀀스if x not in other: break # 포함되지 않으면

else: res.append(x) # 모든 시퀀스에 포함되어 있으면return res >>> from inter import intersect

>>> s1, s2, s3 = 'SPAM', 'SCAM', 'SLAM'>>> intersect(s1, s2)['S', 'A', 'M'] 94Python 기초 교육

함수의 기초

• 인수매칭 방법들: 나머지 인수 모으기def func(spam, eggs=1, *args, **vargs):print (spam, eggs, args, vargs)

>>> func(1,2)(1, 2, (), {})>>> func(1,2,3,4,5,6,7)(1, 2, (3, 4, 5, 6, 7), {})>>> func(1,2,3,4,5,6,7,a=8,b=9)(1, 2, (3, 4, 5, 6, 7), {'a': 8, 'b': 9})

def func2(**kw):print kw

def func1(**kw):func2(**kw)func2(kw) # error

func1(a=1, b=2, c=3)

def func2(*args, **vargs):print args, vargs

def func1(*args, **vargs):func2(*args, **vargs)

func1(1,2,3,a=4,b=5,c=6)

95Python 기초 교육

함수의 기초

• 연습문제1. intersect에 대응하는 union 함수를 만들어 보자.>>> union('SPAM', 'SCAM', 'SLAM') ['S', 'P', 'A', 'M', 'C', 'L']

2. 전달된 모든 인수들의 합과 곱을 구하는 함수를 만들어 보자.>>> sum(1,2,3,4,5,6,7,8,9,10)(55, 3628800)

def sum(*args):sum = 0; mul = 1for x in args:sum += xmul *= x

return sum, mul

def union(*args):res = []for seq in args:for x in seq:if not x in res: res.append(x)

return res

• 파이썬이인수를 매치하는 순서1. 비 키워드 인수를 위치로 치환2. 키워드 인수를 이름으로 매치3. 여분의 비 키워드 인수를 *name 튜플에 치환4. 여분의 키워드 인수를 **name 사전에 치환5. 헤더에 치환되지 않은 인수는 기본값으로 치환 96Python 기초 교육

lambda 함수

• lambda 식 : def를 이용하지 않고 함수 객체를 만드는 방법lambda arg1, arg2, ..., argN: 인수를 사용한 표현식

• lambda 와 def의 차이점– lambda는 표현식이지 문이 아니다. lambda는 값(함수 객체)를 리턴한다.– lambda 몸체는 단일 식이어야 하며, 블록 문이 될 수 없다. lambda 몸체는 def 안에서 return문을 쓰는 것과 유사하다.

>>> def func(x, y, z): return x + y + z...>>> func(2,3,4)9>>> f = lambda x, y, z: x + y + z>>> f(2,3,4)9

>>> func<function func at 0x00B35630>

>>> f<function <lambda> at 0x00B356F0>

• lambda 의 활용L = [lambda x: x**2, lambda x: x**3, lambda x: x**4] # 제곱, 3제곱, 4제곱for f in L: print f(2), # 4, 8, 16 출력print L[0](3) # 9 출력

– lambda 가 없다면 세 개의 def문을 리스트 바깥에 만들어 사용해야 함.

참고

97Python 기초 교육

apply와 map• apply 내장 함수: 함수의 이름이나 인수를 모르는 상태에서 일반화된 형식으로 임의의 함수를 호출한다.

>>> def func(x, y, z): return x + y + z...>>> action = func>>> args = (2, 3, 4)>>> apply(action, args) # action(2, 3, 4)와 같다.9

• map 내장 함수: 함수의 이름이나 인수를 모르는 상태에서 일반화된 형식으로 임의의 함수를 호출한다.>>> counters = [1, 2, 3, 4]>>> def inc(x): return x + 10...>>> map(inc, counters) # [inc(counters[0]), inc(counters[1]), ...][11, 12, 13, 14]>>> map((lambda x: x+3), counters)[4, 5, 6, 7]

참고

98Python 기초 교육

함수 객체

• 함수는객체다: 따라서 간접 호출이 가능def echo(message): # echo는 함수 객체로 치환된다.print message

x = echo # x도 같은 함수 객체를 참조한다.x('Hello world!') # ()로 함수 객체를 호출한다.

def indirect(func, arg):func(arg)

indirect(echo, 'Hello world!') # 함수를 함수로 전달

• 내포된함수는 내포된 영역이 아니다.

if action='add':def func(x, y): return x+y

elif action='multi':def func(x, y): return x*y

- def를 if문 안에 내포하여 다르게 정의하기 - 내포된 함수def outer(x):def inner(i):print i,if i: inner(i-1)

inner(x)outer(3) # 3 2 1 0inner(3) # 오류

참고

99Python 기초 교육

함수의 기본값

• 기본값은함수가 호출될 때가 아니라, def 문이 수행될 때 계산되어 저장된다– 기본값을 갖는 객체는 그대로 유지되기 때문에, 변경이 가능한 기본값을 변경하는 데에는 주의를 기울여야 한다.

def saver(x=[]): # x 변경이 가능한 객체이며 기본값x.append(1) # 변경 가능한 객체를 변경하였음print x

>>> saver([2]) # 기본값이 사용되지 않는다.[2, 1]>>> saver() # 기본 값이 사용된다.[1]>>> saver() # 매번 부를 때 마다 인수 x의 값이 바뀌어 출력된다.[1, 1]>>> saver()[1, 1, 1]

def saver(x=None):if x is None: x = [] # 코드안 초기화, 호출될 때마다 실해됨x.append(1) # 변경 가능한 객체를 변경하였음print x

참고

100Python 기초 교육

http://www.wxpython.org/

wxPython2.8-win32-docs-demos-2.8.11.0.exe

wxPython2.8-win32-ansi-2.8.11.0-py26.exe

설치파일 다운로드

102Python 기초 교육

wxPython2.8-win32-ansi-2.8.11.0-py26.exe 실행

wxPython 설치

103Python 기초 교육

wxPython Demo 설치

wxPython2.8-win32-docs-demos-2.8.11.0.exe 실행

104Python 기초 교육

wxPython Demo 실행

시작 프로그램->wxPython2.8 Docs Demos and Tools-> Run the wxPython DEMO

105Python 기초 교육

클래스의 기초

• 클래스(class)는 ...– 함수나모듈과 같은 파이썬 프로그램의단위– 논리와데이터를 묶어주는 또 다른 구성 성분– 객체를생성하는 틀

• 클래스의 특성– 다중인스턴스: 클래스틀에서객체를찍어낸다

• 클래스로 부터 생성된 객체는 객체 단위마다 다른 값을 갖는 데이터를 위해그 자신의 네임스페이스를 얻는다.

– 상속을통한특성화: 기존에있는클래스를변형시킨다• 클래스 외부에서 클래스의 속성을 오버라이딩(overriding)함으로 확장된다.

– 연산자중복: 클래스객체로연산을한다.• 클래스는 특별한 프로토콜 메소드를 제공함으로써 내장 자료형에서 동작하는연산에 응답하는 객체를 정의할 수 있다.

class <name>(superclass, ...):member = valuedef method(self, ...):self.member = value

• 일반형식

107Python 기초 교육

클래스의 기초

• 예제class FirstClass: # 클래스 객체를 정의def setdata(self, value): # 클래스 메소드를 정의self.data = value # self는 인스턴스

def display(self):print self.data # self.data는 객체마다 존재, 클래스내에서 공유됨

x = FirstClass()y = FirstClass()x.setdata('King Arthur') # 또는 x.data = 'King Arthur'y.setdata(3.14) # 또는 y.data = 3.14x.display()y.display()

x-data

y-data

FirstClass-setdata-display

객체(인스턴스) 클래스• 클래스객체는 메소드를 공유한다.

is-a

is-a

108Python 기초 교육

클래스의 기초

• 클래스상속class SecondClass(FirstClass): # 상속 ()안에 슈퍼클래스를 적어준다def display(self): # 메소드를 변경(재정의)print 'Current value = %s' % self.data

z = SecondClass()z.setdata(42)z.display()

z-data SecondClass

-display

객체(인스턴스) 클래스

FirstClass-setdata-display

is-ais-a

z.data z.diaplay z.setdata

109Python 기초 교육

클래스의 기초

• 클래스연산자 중복 (operator overloading)– 연산자: 더하기(혹은 연결하기), 슬라이싱, 프린팅, 자격부여– __X__와 같은 이름을 가진 메소드는 특별한 훅(hook, 연결)이다.– 이러한 메소드는 파이썬이 연산자를 평가할 때 자동으로 호출된다.– 클래스는 대부분의 내장 자료형 연산을 겹쳐서 쓸 수 있다.– 연산자는 클래스를 파이썬의 객체 모델과 통합하도록 한다.

class ThirdClass(SecondClass):def __init__(self, value): # 새로운 인스턴스 객체가 생성될 때 호출self.data = value

def __add__(self, other): # + 연산return ThirdClass(self.data + other) # 새로운 인스턴스를 만든다

def __mul__(self, other): # * 연산self.data = self.data * other # 인스턴스를 변경한다

a = ThirdClass('abc')a.display() # Current value = abcb = a + 'xyz' # 또는 b = a.__add__('xyz')b.display() # Current value = abcxyza * 3 # 또는 a.__mul__(3)a.display() # Current value = abcabcabc 110Python 기초 교육

클래스의 기초

• 연산자중복 메소드

메소드 중복 연산자 호출될 때__init__ 생성자 객체 생성: Class()

__del__ 소멸자 객체 반환시__add__ 연산자'+' X + Y

__or__ 연산자'-' (비트연산 or) X | Y

__repr__ 프린팅, 변환 print X, 'X'

__call__ 함수호출 X()

__getattr__ 자격부여 X.undefined

__getitem__ 인덱싱 X[key], for 루프, in 테스트__setitem__ 인덱스 치환 X[key] = value

__getslice__ 슬라이싱 X[low,high]

__len__ 길이 len(X), 진리값 테스트__cmp__ 비교 X == Y, X < Y

__radd__ 우측 연산자 '+' 비인스턴스(noninstance) + X111Python 기초 교육

클래스의 기초

• __getitem__ 예제 (인덱스연산)class indexer:def __getitem__(self, index): # 인덱스의 제곱 값을 리턴return index ** 2

>>> X = indexer()>>> for i in range(5):... print X[i],...0 1 4 9 16

class stepper:def __getitem__(self, i):return self.data[i]

>>> Y = stepper()>>> Y.data = 'Spam'>>> for item in Y: print item,...S p a m>>> 'p' in Y # in 연산자도 __getitem__ 메소드를 호출한다.True

(참조) for 루프는 0에서 부터 시작하여 out-of-bound 예외가 발생할 때까지 반복적으로 값이 증가한다. indexer 클래스 객체 X에 대하여for x in X: print x 는 어떤 결과를 내는가? 112Python 기초 교육

클래스의 기초

• __getattr__ 예제 (자격부여 qualification, 속성 참조)class empty:def __getattr__(self, attrname):if attrname == 'age': return 36else: raise AttributeError, attrname # 예외를 발생시킨다

>>> Z = empty()>>> Z.age # X는 age라는 속성을 갖고 있지 않음. __getattr__ 메소드로 전달36>>> Z.nameTraceback (most recent call last):File "<stdin>", line 1, in ?File "<stdin>", line 4, in __getattr__

AttributeError: name

113Python 기초 교육

클래스의 기초

• __getrepr__ 예제 (문자열표현)class adder:def __init__(self, value=0):self.data = value

def __add__(self, other):self.data = self.data + other

def __repr__(self):return self.data

>>> Z = empty()>>> Z.age # X는 age라는 속성을 갖고 있지 않음. __getattr__ 메소드로 전달36>>> Z.nameTraceback (most recent call last):File "<stdin>", line 1, in ?File "<stdin>", line 4, in __getattr__

AttributeError: name

114Python 기초 교육

예외의 기초

• 예외(exception)란?– 프로그램제어의 흐름을 수정하는 사건– 일종의 “강력한 GOTO”와같은 기능

• 예외 관련 문– try: 발생된 예외를 검출한다.– raise: 예외를 직접 발생한다.

• 예외는 발생되는 경우– 실행시오류 (예, division by zero)– 프로그램에서 explicitly raise되는경우

• 파이썬 인터프리터의 예외 처리– 프로그램에서 예외가 처리되지 않으면 인터프리터는 프로그램의 실행을 중단하고, 스택 추적을 프린트한다. (단, SystemExit예외의 경우는 제외)

116Python 기초 교육

예외의 기초• 예외상황

>>> import unknownTraceback (most recent call last):File "<stdin>", line 1, in ?

ImportError: No module named unknown

>>> a = 1 / 0Traceback (most recent call last):File "<stdin>", line 1, in ?

ZeroDivisionError: integer division or modulo by zero

>>> a = []; print a[3]Traceback (most recent call last):File "<stdin>", line 1, in ?

IndexError: list index out of range

>>> a = {}; print a.unknownTraceback (most recent call last):File "<stdin>", line 1, in ?

AttributeError: 'dict' object has no attribute 'unknown'

>>> 'abc' * 3.14Traceback (most recent call last):File "<stdin>", line 1, in ?

TypeError: can't multiply sequence by non-int

117Python 기초 교육

예외의 기초• 예외상황

>>> file = open("/unknown")Traceback (most recent call last):File "<stdin>", line 1, in ?

IOError: [Errno 2] No such file or directory: '/unknown'

• 발생가능 한 예외는 dir(__builtins__) 을 참조 (Built-in Exceptions)– http://www.python.org/doc/current/lib/module-exceptions.html 118Python 기초 교육

예외의 기초

• 예제# bad.pydef gobad(x, y):

return x / ydef func(x):

print gobad(x, 0)func(1)

$ python bad.pyTraceback (most recent call last):

File "bad.py", line 6, in ?func(1)

File "bad.py", line 5, in funcprint gobad(x, 0)

File "bad.py", line 3, in gobadreturn x / y

ZeroDivisionError: integer division or modulo by zero

• 파이썬은 검출되지 않은 예외가 발생하면 프로그램을 중단시키고, 스택 추적과 발생된 예외의 이름과 추가의 데이터를 출력한다.

예외가 발생 했을 때 활성화되어 있는 모든 함수를 이전 것에서 새로운것의 순서로 파일명, 행번호, 소스 코드를 보여준다.

119Python 기초 교육

예외의 기초• try/except/else 문

try:<statements> # 문의 실행

except <name>:<statements> # try 블록을 실행 중에 ‘name’이 발생

except <name>, <data>:<statements> # ‘name’ 발생(데이터도 받는다)

else:<statements> # 예외가 발생하지 않음

try:import unknown

except ImportError:print "can't import module"

else: pass

try:div = a / b

except ZeroDivisionError:print "division by zero exception"

except NameError, e:print "Errrrrrrror!", e

try:div = a / b

except ZeroDivisionError:print "b is zero"

else:print 'else'

try:div = a / b

except (ZeroDivisionError, NameError):print "this is an exceptions"

• 예제

120Python 기초 교육

예외의 기초

• try/finally 문try:

<statements>finally:

<statements> # 언제나 나갈 때 수행

# finally.pydef divide(x, y):return x / y

def tester(y):try:print divide(8, y)

finally:print 'on the way out...'

print 'Test 1:'; tester(2)print 'Test 2:'; tester(0)

• 예제$ python finally.pyTest 1:4on the way out...Test 2:on the way out...Traceback (most recent call last):File "finally.py", line 10, in ?print '\nTest 2:'; tester(0)

File "finally.py", line 6, in testerprint divide(8, y)

File "finally.py", line 3, in dividereturn x / y

ZeroDivisionError: integer division or modulo by zero

• try블록 수행 중에 예외가 발생 했을 때 finally문을 수행한다. 그리고 나서 예외를 최상위 수준의try로 전달한다. try 문 이후는 수행되지 않는다.

• finally 블록은 try 블록 안에서 예외 발생과 관계없이 언제나 try문을 빠져나갈 때 수행된다.121Python 기초 교육

예외의 기초

• raise 문raise <name> # 프로그램에서 직접 예외를 발생raise <name>, <data> # 추가의 데이터를 전달

– 예외 이름은 내장 예외 이름과 사용자가 정의한 예외 일 수 있다.– 예외는 객체에 의해서 식별되며, 한 순간에 하나만이 활성화된다.– 한번 except절에 의하여 잡히면, 예외는 끝이나지만, raise 혹은 에러가 다시 발생하는 경우에는 예외가 다시 발생한다.

MyError = 'my error'def stuff(file):raise MyError

file = open('data', 'w')try:stuff(file)

finally: # 함수에서 예외 발생 유무에 상관없이 언제나 파일이 닫힌다.print 'closing file' file.close()

• 예제

122Python 기초 교육

예외의 기초• 중첩된 try문

# try1.pymyError = 'error'try:try:raise myError

except:print "inner"

print "continue1"except:print "outer"

print "continue2"

innercontinue1continue2

# try2.pymyError = 'error'def func():try:raise myError

except:print "func"

print "continue1"

try:func()

except:print "caller"

print "continue2"

# try3.pymyError = 'error'def func():try:raise myError

finally:print "func"

print "continue1"

try:func()

except:print "caller"

print "continue2"

funccontinue1continue2

funccallercontinue2

123Python 기초 교육

예외의 관용구

while 1:try:

line = raw_input()except EOFError:

breakelse:

print 'line:[%s]' % line

• 표준 입력 스트림에서 데이터를 읽기

윈도우C:\>python input.pyhelloline:[hello]worldline:[world]^Z [Enter] 종료

리눅스$ python input.pyhelloline:[hello]worldline:[world]^D 종료

124Python 기초 교육

예외의 관용구

# loop.pyimport sysdef loop():

while True: passtry:

loop()except KeyboardInterrupt:

print "program exits"sys.exit(0)

• CTRL-C처리

C:\> python loop.pyyou press Ctrl-C

C:\>

# while.pyimport timetry:

while (True):print "hello"time.sleep(0.1)

except KeyboardInterrupt:print "keyboard interrupt"

C:\> python while.pyhellohellohelloKeyboard interrupt

C:\>

참고

125Python 기초 교육

예외 클래스

• 클래스 예외는 계층구조의 구성을 지원한다.– 일반적인 예외 수퍼클래스에 이름을 부여함으로써 except절이 전체 예외의 범주를 검출할 수 있다.

# excclass.pyclass General: passclass Specific(General): pass

def raiser1():X = General()raise X # 클래스 인스턴스의 예외 발생

def raiser2():X = Specific()raise X # 서브클래스 인스턴스의 예외 발생

for func in (raiser1, raiser2):try:func()

except General: # General 또는 그 서브클래스를 검출import sysprint 'caught:', sys.exc_type

$ python excclass.pycaught: __main__.Generalcaught: __main__.Specific

• 내장된 예외 ArithmeticError는 OverflowError와 ZeroDivisionError와 같은 구체적인 예외의 수퍼클래스이다. 그러나 ArithmeticError를 검출함으로써, 그것의 서브클래스가발생한 수치 에러의 다양한 종류를 모두 검출할 수 있다.

참고

126Python 기초 교육

The class hierarchy for built-in exceptions

Built-in Exceptions참고

127Python 기초 교육

모듈의 기초

• 왜 모듈을 사용하는가?– 코드의재사용: 모듈 파일에 코드를 작성한다.– 시스템네임스페이스의분할: 모든 코드와 객체는 언제나 모듈안에 존재한다.

• 모듈 생성– 파이썬파일, C언어 확장 파일

• 모듈 사용– import 문, from 문, reload() 내장 함수

• 모듈 검색 경로: PYTHONPATH 환경 변수– sys.path 내장 리스트를 이용하여 검색 경로 변경 가능

129Python 기초 교육

모듈의 기초# module1.pydef printer(X):print X

>>> import module1 # 모듈 가져오기>>> module1.printer('Hello world!') # module.nameHello world!

>>> from module1 import printer # 모듈에 지정된 이름만을 가져온다>>> printer('Hello world!') # 자격을 부여할 필요가 없다Hello world!

>>> from module1 import * # 최상위 수준에서 치환된 모든 이름을 가져옴>>> printer('Hello world!')Hello world!

130Python 기초 교육

모듈의 기초

• 모듈 파일은 네임스페이스이다– 모듈 내부의 문은 처음 가져올 때 수행된다.

• 빈 모듈 객체를 생성하고 파일 안에 있는 문을 하나씩 수행한다.– 상위 수준의 치환문은 모듈의 속성을 생성한다.

• 최상위수준에 있는 이름을 치환하는문은 모듈 객체의 속성으로 생성된다.

– 모듈 네임스페이스: 속성 __dict__ 또는 dir()• 모듈네임스페이스는 __dict__속성이나 dir()함수를 이용하여 확인할수 있다.

– 모듈은 단일 영역이다(지역 영역이 전역 영역이다)• import는 단 한번만 실행된다.

– 모듈은 첫번째 import 혹은 from에서만 실제로 실행된다.– 모듈의 코드를 실행시키면 최상위 수준의 이름을 생성한다.– 이 후의 import와 from은 이미 적재된 모듈을 사용한다.

131Python 기초 교육

모듈의 기초# simple.pyprint 'hello'spam = 1

>>> import simple # 모듈을 처음으로 가져온다hello # print 문이 실행된다.>>> simple.spam1>>> simple.spam = 2 # 모듈의 속성값을 바꾼다.>>> import simple # 모듈을 다시 가져온다. print 문이 실행 안됨>>> simple.spam2>>> reload(simple) # 모듈을 재적재한다hello<module 'simple' from 'simple.pyc'>>>> simple.spam1

• 모듈을 불러오면 컴파일된 .pyc 바이트코드 파일이 생성된다. 파이썬은 모듈에 대한 .py 소스 파일이 검색 경로에 없을 경우에 .pyc 파일을 적재한다.

• 모듈 M을 가져왔을 때, M.py파일이 M.pyc 바이트코드가 저장된 후 변경이 되지 않았다면 파이썬은 M.pyc 바이트코드 파일을 M.py 소스 파일 대신 적재한다.

132Python 기초 교육

모듈의 기초# simple.pyprint 'hello'spam = 1_hidden = 99 # 언더스코어로 시작된 이름은 from * 문으로 가져올 수 없다

>>> from simple import *hello>>> dir()['__builtins__', '__doc__', '__name__', 'spam']

• 각 모듈은 __name__ 이라고 불리는 내장된 속성을 가지고 있다.• 모듈이 프로그램으로 수행되면, __name__은 ‘__main__’문자열로 설정된다.

# tester.pydef tester():print “It's Christmas in Heaven...”

if __name__ == '__main__': # 프로그램으로 실행할 때만tester()

$ tester.pyIt's Christmas in Heaven...$ python>>> import tester>>> tester.tester()It's Christmas in Heaven...

133Python 기초 교육

type(), str()>>> type(1)<type 'int'>>>> li = []>>> type(li)<type 'list'>>>> import string>>> type(string)<type 'module'>>>> a = 1; b = 'z'; print type(a) == type(b)False>>> str(123)'123'>>> str(3.14)'3.14'>>> horsemen = ['war', 'pestilence', 'famine']>>> str(horsemen)"['war', 'pestilence', 'famine']">>> str(string)"<module 'string' from 'c:\\python24\\lib\\string.pyc'>"

참고

134Python 기초 교육

>>> import string>>> string.punctuation'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'>>> string.join<function join at 0x00B46A30>>>> callable(string.punctuation)False>>> callable(string.join)True

callable()참고

135Python 기초 교육

python encoding.pysys:1: DeprecationWarning: Non-ASCII character '\xb0' in file euckr.py on line 3, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

소스코드 인코딩 정의# encoding.py# _*_ coding: euc_kr _*_

buf = '가나다‘ # 한글

이 라인이 없으면 아래와 같은Warning 이 발생한다.

참고

136Python 기초 교육

파일 처리의 기초• 파일 객체는 파이썬 내장 타입의 인스턴스이다.• 내장 함수 open()은 파일 객체를 생성한다.

– 첫 번째 인자(引子, argument)는 파일의 경로를 나타냄. '/'문자는 파일경로를 구분함 (유닉스, 윈도우에 공통으로 사용)

– 두 번째 인자는 파일을 여는 방법(모드)• 'r': 텍스트 모드로 읽기 (디폴트), 'rb': 바이너리 모드로 읽기• 'w': 텍스트 모드로 쓰기, 'wb': 바이너리 모드로 쓰기

input = open('data', 'r')output = open('/tmp/spam', 'w')output = open('C:\\temp\\spam', 'w')

• 파일 객체의 close() 메소드는 파일을 닫는다.>>> output = open('data', 'w')>>> output<open file 'data', mode 'w' at 0x00B23698>>>> output.close()>>> output<closed file 'data', mode 'w' at 0x00B23698>

• 파일에 쓰기 위해서는 write() 메소드를 호출한다.output.write(s) # s는 문자열

138Python 기초 교육

파일 처리의 기초• 파일에서 읽기

•file.read() returns a string containing all the bytes stored in the file.•file.read(N) returns a string containing the next N bytes from the file.•file.readline() reads through the next \n and returns a line string.•file.readlines() reads the entire file and returns a list of line strings.– read()와 readlines()는 파일 전체를 읽어들이고,– read(N)와 readline()는 파일의 일부분을 읽어들인다.

• Windows 시스템에서 줄바꿈 문자의 처리•텍스트 모드에서 읽을 때 \r\n은 \n으로 변환된다.•텍스트 모드에서 쓸 때 \n은 \r\n으로 변환된다.•바이너리 모드에서는 어떤 변환도 일어나지 않는다.•유닉스타입의 플랫폼에서는 open mode에 관계없이 어떤 변환도 하지 않음

139Python 기초 교육

파일 처리의 기초• 파일을 읽어서 라인 단위로 처리

– readline() 메소드input = open('data.txt', 'r')while 1:

line = input.readline()if not line: breakprint line # 라인단위로 처리

input = open('data.txt', 'r')for line in input.readlines():

print line # 라인단위로 처리

• 파일 전체를 문자열 리스트에 한꺼번에 읽어서 한 줄씩 처리– readlines() 메소드 : 파일크기가메모리크기보다작을때 유용하다.

input = open('data.txt', 'r')for line in input.xreadlines():

print line

• xreadlines()메소드: 파일 크기에 관계없이 일정량의 메모리만 사용한다.

• 파일 객체 자체에 대해 for 루프를 돌리는 방법, xreadlines()와 동일input = open('data.txt', 'r') # python 2.2 이상for line in input: print line

xreadlines( ) Deprecated since release 2.3.Use "for line in file" instead

140Python 기초 교육

파일 처리의 기초• Portability(이식성) and Flexibility(융통성)

– 파일 인터페이스는 거의 모든 플랫폼에서 동일하다.– 파일 이외의 객체를 파일처럼 처리가 가능하다.

# myutils.pydef scanner(fileobject, linehandler):for line in fileobject.readlines():linehandler(line)

from myutils import scannerdef firstword(line): print line.split()[0]file = open('data.txt')scanner(file, firstword)

from cStringIO import StringIOfrom myutils import scannerdef firstword(line): print line.split()[0]string = StringIO('one\ntwo xxx\nthree\n')scanner(string, firstword)

• 문자열 객체를 파일처럼 활용할 수 있다.

class MyStream:def readlines(self):return ['a\n', 'b c d\n']

from myutils import scannerdef firstword(line): print line.split()[0]object = MyStream()scanner(object, firstword)

• readlines()메소드를 갖는 클래스 객체를 만들어 파일처럼 활용할 수 있다.

ActionsAAfterThereNoOneManyStrikeNoPractice

onetwothree

ab

141Python 기초 교육

파일 처리의 기초• 파일내용전체를하나의문자열로읽고쓰기all_the_text = open('data.txt').read() # text fileall_the_text = open('data.txt', 'rb').read() # binary file

file = open('data.txt') # 읽기all_the_text = file.read()file.close()

file = open('output.txt', 'w') # 쓰기file.write(all_the_text)file.close()

# 문자열의 리스트를 파일에 쓴다file = open('output.txt', 'w') # 쓰기list_of_text_strings = ['a', 'b xxx', 'c']file.writelines(list_of_text_strings)file.close()

Actions speak louder than words.A drowning man will catch[grasp] at a straw.After a storm comes a calm. There is no rest for a family(mother) with many children.No pains, no gains.One swallow does not make a summer.Many drops make a shower.Strike while the iron is hot.No news is good news.Practice makes perfect.

data.txt

142Python 기초 교육

파일 처리의 예제• 파일에서특정문자열을찾아바꾸기# replace.pyimport os, sysnargs = len(sys.argv) # 명령행 인자의 개수if not 3 <= nargs <= 5:

print "usage: %s search_text replace_text [infile [outfile]]" % \os.path.basename(sys.argv[0])

else:stext = sys.argv[1] # 찾을 문자열rtext = sys.argv[2] # 바꿀 문자열input = sys.stdin # 표준 입력output = sys.stdout # 표준 출력if nargs > 3: # replace.py 찾을문자열 바꿀문자열 입력파일 출력파일input = open(sys.argv[3]) # 입력파일

if nargs > 4:output = open(sys.argv[4], 'w')

for s in input: # 문자열 객체의 replace 메소드를 이용하여 단어를 바꾼다output.write(s.replace(stext, rtext))

output.close()input.close()

# replace make "**MAKE**" data.txt output.txt

143Python 기초 교육

os모듈에서 제공하는 파일처리함수• os 모듈에서 파일 처리 함수들을 제공한다.

– 제공하는 함수들• descriptor = os.open(path, flags, mode)• os.read(descriptor, N)• os.write(descriptor, string)• os.lseek(descriptor, position)

– descriptor는 운영체제에서 파일을 다루는 핸들과 동일하다.– descriptor기반의 파일 처리 함수들은 파이썬 내장 파일 객체보다 더 low-level 수준이며, 사용법은 더 복잡하다.

– 특수한 목적의 파일 처리가 아니라면 파이썬 내장 객체를 사용하는 것이 좋다.

– Python Library Reference(6.1.3 File Descriptor Operations) 를 참조

파이썬 내장 파일 객체의 fileno() 메소드는 정수형 descriptor값을 리턴한다.

>>> file = open('a.txt','w')>>> file.fileno()4

>>> from sys import stdin, stdout, stderr>>> stdin.fileno(), stdout.fileno(), stderr.fileno()(0, 1, 2)

144Python 기초 교육

os모듈에서 제공하는 파일처리함수>>> sys.stdout.write('Hello stdin world\n') # write via file methodHello stdin world>>> import os>>> os.write(1, 'Hello descriptor world\n') # write via os moduleHello descriptor world23

• Open 모드 플래그>>> open('temp.txt','w').write('Hello56789abcdefghijkl\n')>>> import os>>> fdfile = os.open('temp.txt', (os.O_RDWR | os.O_BINARY))>>> os.read(fdfile, 20)'Hello56789abcdefghij'>>> os.lseek(fdfile, 0, 0) # go back to start of file0L>>> os.read(fdfile, 100)'Hello56789abcdefghijkl\r\n'>>> os.lseek(fdfile, 0, 0)0L>>> os.write(fdfile, 'HELLO') # overwrite first 5 bytes5>>> os.close(fdfile)

flags•O_RDONLY •O_WRONLY•O_RDWR•O_APPEND•O_CREAT•O_EXCL•O_TRUNC

145Python 기초 교육

그 외 os모듈의 파일 처리 방법os.chmod('spam.txt', 0777) # enable all accesses

os.rename('spam.txt', 'eggs.txt') # rename file

os.remove('spam.txt') # delete file

# stat 시스템 콜의 결과를 보여준다.

>>> info = os.stat('temp.txt')

(33206, 0L, 18, 1, 0, 0, 24L, 1146104115, 1146104115, 1146103927)

참고>

(MODE, INO, DEV, NLINK, UID, GID SIZE, ATIME, MTIME, CTIME)

stat 모듈은 os.stat결과를 일관되게 처리할 수 있는 방법을 제공한다.

>>> import stat

>>> info[stat.ST_MODE], info[stat.ST_SIZE]

(33206, 24L)

>>> mode = info[stat.ST_MODE]

>>> stat.S_ISDIR(mode), stat.S_ISREG(mode) # directory or regular file

(False, True)

# 디렉토리/파일 종류와 파일 크기를 구하는 다른 방법 os.path 모듈

>>> path = 'temp.txt'

>>> os.path.isdir(path), os.path.isfile(path), os.path.getsize(path)

(False, True, 24L)146Python 기초 교육

디렉토리 파일 목록 구하기

import os

dir = os.popen('dir /B').readlines() # dir 명령을 이용하므로 플랫폼에 의존적

# dir = os.popen('dir /B *.py').readlines()

for item in dir:

print item[:-1] # \n 문자를 제거하고 출력

• os.popen을 이용하여 shell 명령을 실행

• glob 모듈을 이용>>> import glob

>>> glob.glob('*')

>>> glob.glob('*.html')

>>> glob.glob('????.txt')

>>> glob.glob('subdir/*')

• os.listdir 호출>>> import os

>>> os.listdir('.')

>>> os.listdir(os.curdir)

>>> os.listdir('subdir')

147Python 기초 교육

디렉토리 파일 목록 구하기

import os

def listdir(dirname):

result = []

for file in os.listdir(dirname):

fullpath = os.path.join(dirname, file)

result.append(fullpath)

return result

>>> for item in listdir('c:\\'): print item

• os.path.join()

• os.path.walk(): 디렉토리 트리 방문# lister.py

import sys, os

def lister(dummy, dirname, filesindir):

print '[' + dirname + ']'

for fname in filesindir:

print os.path.join(dirname, fname)

if __name__ == '__main__':

os.path.walk(sys.argv[1], lister, None)

Python Reference Library - 6.2 os.path 참조

# Windows

python lister.py C:\

# Unix/Linux

python lister.py /home

148Python 기초 교육

디렉토리 파일 목록 구하기# python lister.py /tmp

[/tmp]

/tmp/.font-unix

/tmp/mysql.sock

/tmp/a

/tmp/b

/tmp/sess_f51de6bdd3f464e89029d827c79292ba

/tmp/hsperfdata_root

[/tmp/.font-unix]

/tmp/.font-unix/fs7100

[/tmp/a]

/tmp/a/b

[/tmp/a/b]

[/tmp/hsperfdata_root]

149Python 기초 교육

sys 모듈

• sys.path– import 할 때 참조하는 디렉토리 목록

• sys.modules– 현재 세션에 적재된 모듈의 사전

• sys.platform– 플랫폼을 나타내는 문자열 (win32, mac, osf1, linux-x386,

sunos4)• sys.ps1, sys.ps2

– 인터프리터에서 1차, 2차 프롬프트로 사용되는 두 개의 출력객체 기본값은 >>>와 ... 이다.

• sys.argv– 명령행 입력 단어 리스트

• sys.stdin, sys.stdout, sys.stderr– 표준 입력, 표준 출력, 에러 출력

150Python 기초 교육

연습문제

• 지정한 파일을 일정한 길이로 잘라주는 함수file_split(filename, size) 와 잘려진 파일을 하나로합쳐주는 file_join(filenames, filename) 함수를 만들어 보자.– ex)

file_split('bigfile', 1024*1024)– 'bigfile' 파일을 1MB크기로 잘라서. bigfile.0, bigfile.1, bigfile.2, ... 의 파일 이름으로 저장한다.

file_join(('bigfile.0', 'bigfile.1', 'bigfile.2'), 'bigfile')– 파일을 순서대로 하나의 파일로 합친다.

151Python 기초 교육

IDLE (Python GUI)시작 -> 프로그램 -> Python 2.4 -> IDLE(Python GUI)

참고

152Python 기초 교육

IDLE (Python GUI)

• Python Source Editing– Syntax highlighting– Indent/Dedent Region– Comment Out/Uncomment Region– Tabify/Untabify Region

참고

153Python 기초 교육

marshal 모듈• Serialize a Python data structure composed of only

fundamental Python objects (e.g., lists, tuples, numbers, and strings, but no classes, instances, etc)

data = {12:'twelve', 'feep':list('ciao'), 1.23:4+5j, (1,2,3):u'wer'}import marshalbytes = marshal.dumps(data)>>> bytes'{t\x04\x00\x00\x00feep[\x04\x00\x00\x00t\x01\x00\x00\x00ct\x01\x00\x00\x00it\x01\x00\x00\x00at\x01\x00\x00\x00of\x041.23x\x034.0\x035.0i\x0c\x00\x00\x00t\x06\x00\x00\x00twelve(\x03\x00\x00\x00i\x01\x00\x00\x00i\x02\x00\x00\x00i\x03\x00\x00\x00u\x03\x00\x00\x00wer0'>>> len(bytes)99

reconstructed_data = marshal.loads(bytes)print reconstructed_data>>> print reconstructed_data{12: 'twelve', 1.23: (4+5j), 'feep': ['c', 'i', 'a', 'o'], (1, 2, 3): u'wer'}>>> data == reconstructed_dataTrue

• dumps/loads는 machine architecture에 관계없이 동일하게 동작된다.– 파이썬 버젼이 같기만 하면 됨. 155Python 기초 교육

marshal 모듈

• dump(value, file, [, version])– 객체 value를 열려진 파일 file 에 기록한다.

• load(file)– 열려진 파일 file에서 하나의 value를 읽어서 반환한다.

• dumps(value[, version])– 객체 value를 문자열로 바꾸어 반환한다. ( dump(value, file)에서 파

일에 기록될 데이터를 문자열로 반환. )• loads(string)

– dumps서 반환된 문자열을 원래 값으로 반환한다.

Python Library Reference 참조156Python 기초 교육

marshal 모듈ouf = open('datafile.dat', 'wb')marshal.dump(data, ouf)marshal.dump('some string', ouf)marshal.dump(range(19), ouf)ouf.close()

inf = open('datafile.dat', 'rb')a = marshal.load(inf)b = marshal.load(inf)c = marshal.load(inf)inf.close()print a, b, c>>> print a, b, c{12: 'twelve', 1.23: (4+5j), 'feep': ['c', 'i', 'a', 'o'], (1, 2, 3): u'wer'} some string [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]

(참고) 사전의 경우 직렬화 전과 후에 키의 배열 순서는 달라질 수 있다.157Python 기초 교육

연습문제

• 0에서 1사이의 실수형 데이터 10개를 랜덤하게 생성하고 파일에 저장하고 다시 불러들여보자.# save.py

import random

# 랜덤 넘버 생성

floats = []; count = 0

while (count < 10):

f = random.uniform(0,1)

floats.append(f)

count += 1

print floats

import marshal # marshal 모듈을 이용

file = open('file1.data', 'wb')

for f in floats:

file.write(marshal.dumps(f))

file.close()

import struct # struct 모듈을 이용

file = open('file2.data', 'wb')

for f in floats:

file.write(struct.pack('d', f))

file.close()

# load.py

import marshal

file = open('file1.data', 'rb')

list1 = []

while True:

try: f = marshal.load(file)

except EOFError: break

list1.append(f)

file.close()

import struct

file = open('file2.data', 'rb')

list2 = []

size = struct.calcsize('d')

while True:

s = file.read(size)

if not s: break

(f,) = struct.unpack('d', s)

list2.append(f)

file.close()

print list1 ; print list2

print list1 == list2158Python 기초 교육

pickle, cPickle 모듈• Serializing data (데이터 직렬화)

– 직렬화할 데이터가 기본적인 파이썬 객체로만 구성되어 있음을 보장할수 없거나, 서로 다른 파이썬 버전에 호환성을 유지하고 싶은 경우, 또는텍스트 스트링으로 직렬화를 원한다면 cPickle을 사용한다.

– The pickle module is a pure-Python equivalent, but it's far slower and not worth except if you're missing cPickle.

data = {12:'twelve', 'feep':list('ciao'), 1.23:4+5j, (1,2,3):u'wer'}import cPickletext = cPickle.dumps(data) # serialize to a text stringbytes = cPickle.dumps(data, 1) # serialize to a binary string

redata1 = cPickle.loads(text)redata2 = cPickle.loads(bytes)>>> data == redata1True>>> data == redata2True

159Python 기초 교육

(dp1S'feep'p2(lp3S'c'aS'i'aS'a'aS'o'asF1.23c__builtin__complexp4(F4F5tRp5sI12S'twelve'p6s(I1I2I3tp7Vwerp8s.

>>> data = {12:'twelve', 'feep':list('ciao'), 1.23:4+5j, (1,2,3):u'wer'}>>> cPickle.dumps(data)

피클링 된 데이터

160Python 기초 교육

pickle, cPickle 모듈• dump(obj, file[, protocol[,bin]])

– Write a pickled representation of obj to the open file object file.• load(file)

– Read a string from the open file object file and interpret it as a pickle data stream.

• dumps(obj[,protocol[,bin]])– Return the picked representation of the object as a string,

instead of writing it to a file.• loads(string)

– Read a pickled object hierarchy from a string.

Python Library Reference 참조161Python 기초 교육

pickle, cPickle 모듈ouf = open('datafile.dat', 'w')

cPickle.dump(data, ouf)

cPickle.dump('some string', ouf)

cPickle.dump(range(19), ouf)

ouf.close()

inf = open('datafile.dat', 'r')

a = cPickle.load(inf)

b = cPickle.load(inf)

c = cPickle.load(inf)

inf.close()

print a, b, c>>> print a, b, c

{12: 'twelve', 1.23: (4+5j), 'feep': ['c', 'i', 'a', 'o'], (1, 2, 3): u'wer'} some

string [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]

162Python 기초 교육

pickle, cPickle 모듈import cPickleclass FirstClass: # 클래스 정의def setdata(self, value):

self.data = valuedef display(self):

print self.data

x = FirstClass() # 클래스 객체 생성x.setdata(3.14)p_x = cPickle.dumps(x) # 클래스 객체의 직렬화x2 = cPickle.loads(p_x) # 逆직렬화x2.display()

p_FirstClass = cPickle.dumps(FirstClass) # 클래스 직렬화FirstClass2 = cPickle.loads(p_FirstClass)y = FirstClass2()>>> y<__main__.FirstClass instance at 0x00B3AD28>>>> FirstClass2<class __main__.FirstClass at 0x00B31AB0>

163Python 기초 교육

pickle, cPickle 모듈# 클래스 인스턴스 피클링import cPickleclass ForExample:

def __init__(self, *stuff): self.stuff = stuffanInstance = ForExample('one', 2, 3)saved = cPickle.dumps(anInstance)reloaded = cPickle.loads(saved)assert anInstance.stuff == reloaded.stuff

# 파일 객체는 피클링할 수 없다anotherInstance = ForExample(1, 2, open('three', 'w'))wontWork = cPickle.dumps(anotherInstance)Traceback (most recent call last):File "<stdin>", line 1, in ?File "C:\Python24\lib\copy_reg.py", line 69, in _reduce_ex

raise TypeError, "can't pickle %s objects" % base.__name__TypeError: can't pickle file objects

164Python 기초 교육

pickle, cPickle 모듈# 파일 객체에 피클링 적용하기 ( Python Cookbook 예제 )import typesclass PrettyClever:

def __init__(self, *stuff): self.stuff = stuffdef __getstate__(self): # 객체를 serialize 할 때 호출됨

def normalize(x):if type(x) == types.FileType:return 1, (x.name, x.mode, x.tell())

return 0, xreturn [ normalize(x) for x in self.stuff ]

def __setstate__(self, stuff): # 객체를 deserialize 할 때 호출됨def reconstruct(x):

if x[0] == 0:return x[1]

name, mode, offs = x[1]openfile = open(name, mode)openfile.seek(offs)return openfile

self.stuff = tuple([reconstruct(x) for x in stuff])

import cPicklefile = open('data.txt', 'wb')pc = PrettyClever(1,2,file)saved = cPickle.dumps(pc)reloaded = cPickle.loads(saved)file2 = reloaded.stuff[2]file2.write('hello world')file2.close() 165Python 기초 교육

shelve 모듈• A 'shelf' is a persistent, dictionary-like object.

– The values in a shelf can be essentially arbitrary Python objects -- anything that the pickle module can handle. This includes most class instances, recursive data types, and objects containing lots of shared sub-objects.

– The keys are ordinary strings.import shelveshe = shelve.open('try.she', 'c')for c in 'spam': she[c] = {c:23}>>> she{'a': {'a': 23}, 'p': {'p': 23}, 's': {'s': 23}, 'm': {'m': 23}}>>> for c in she.keys(): print c, she[c]p {'p': 23}s {'s': 23}a {'a': 23}m {'m': 23}>>> she.close()

166Python 기초 교육

shelve 모듈>>> import shelve>>> she = shelve.open('try.she', 'c')>>> for c in 'spam': she[c] = {c:23}>>> she{'a': {'a': 23}, 'p': {'p': 23}, 's': {'s': 23}, 'm': {'m': 23}}>>> she.close()

>>> she['p']['p'] = 42>>> she['p'] # 값이 바뀌지 않았다. temporary 객체를 이용하기 때문{'p': 23}>>> a = she['p']>>> a['p'] = 42>>> she['p'] = a>>> print she['p']

167Python 기초 교육

top related