349
PYTHON 이이이이 Moon Yong Joon

파이썬정리 20160130

Embed Size (px)

Citation preview

Page 1: 파이썬정리 20160130

PYTHON 이해하기Moon Yong Joon

Page 2: 파이썬정리 20160130

DATA(OBJECT) TYPE

Page 3: 파이썬정리 20160130

Data(Object) Type 기본

Page 4: 파이썬정리 20160130

Values and data types: 원자 파이썬은 실제 리터럴 즉 값이 객체이므로 기본 객체의 구성을 이해해야

>>> type(1.1) <class ‘float'>>>> >>> type(17) <class 'int'>

값을 type() 함수를 이용해 데이터 타입을 확인

referencetypevalue

float 주소

1.1

referencetypevalue

int 주소

17

데이터 관리 방안 ( 예시 )

Page 5: 파이썬정리 20160130

Values and data types: 분자 프로그램 언어에서 가장 기본적인 것인 Value 가 가진 형식이 데이터 타입

referencetype

element

referencetypevalue

int 주소1

referencetype

elementlist 주소

referencetypevalue

referencetypevalue …

주소list

>>> v = [1,2,[3,4]]>>> v[1, 2, [3, 4]]>>>

Page 6: 파이썬정리 20160130

Data types 이해하기 int 등 data type 의 키워드는 클래스 객체이고 type 클래스 객체를 구현해서 처리

>>> int.__class__.__name__'type'>>> intobj =1>>> intobj.__class__.__name__'int'>>> isinstance(intobj.__class__, type)True>>> intobj2 = int(1)>>> intobj21>>> intobj2.__class__.__name__'int'>>> type.__class__.__name__'type'>>>

생성된 int 타입이 type 클래스 객체를 상속여부 확인

Page 7: 파이썬정리 20160130

Value and Type : 예시 다양한 타입에 대한 타입과 값을 함수를 통해 처리하는 법 obj.__class__.__name__

• obj.__class__ 의 값은 타입 클래스의 인스턴스 • 타입클래스의 __name__ 속성은 타입에 대한 스트링 관리

def typeof(obj) : return obj.__class__

def valueof(obj) : if obj.__class__ == type(obj) : print(eval(obj.__class__.__name__ + '(obj)')) return eval(obj.__class__.__name__ + '(obj)')

print(typeof(1))print(valueof(1))

print(typeof(1.1))print(valueof(1.1))

print(typeof([1,2]))print(valueof([1,2]))

# 결과값<type 'int'>11<type 'float'>1.11.1<type 'list'>[1, 2][1, 2]

Page 8: 파이썬정리 20160130

타입 특성 데이터를 관리하는 기준이며 파이썬은 최상위 타입을 Object 로 선정해서 모든 것을 object instance 로 처리

>>> type(object)<type 'type'>>>> type(1)<type 'int'>>>> isinstance(1,object)True>>>

Object 를 최상위 클래스 객체이며 이를 상속받아 구현숫자 1 도 실제 자연수라는 클래스객체에서 생성된 객체라서 Ob-ject 이 인스턴스 객체

Page 9: 파이썬정리 20160130

Builtin type 특성객체 내부에 정해진 값이 변경이 가능한지를 구분

=> 컨테이너 타입 중에 실제 값이 정해지지 않은 경우 요소들을 변경이 가능 변경불가 (immutable) : int, float, complex, str/unicode bytes, tuple, frozenset

변경가능 (mutable) : list, dict, set, bytes-array

Page 10: 파이썬정리 20160130

Mutable & immutable

Page 11: 파이썬정리 20160130

Mutable & immutableValues 내부의 값을 변경이 가능한지 점검하여 값을 변경 .특히 variables, 함수 파라미터에 복사할 경우 실제 값 객체가 변경가능여부에 따라 다른 경우가 발생함Mutable 은 주로 리스트 , 딕셔너리 타입으로 내부 값인 요소에 추가하는 것이므로 변수나 함수 파라미터로 사용해도 변경( swallow copy 사용 )

Mutable 처리할 경우 처음이 값이 변경되지 않으려면 참조만 복사하지 말고 전체 값을 복사해야 별도의 참조가 생겨 다른 값 객체로 인식함 (deepcopy 이용 )

Page 12: 파이썬정리 20160130

Mutable & immutable 예시ismutable 함수를 만들어서 실제 값들이 변경여부를 점검한 후에 처리할 수 있으면 좋다

# 함수를 정의해서 각 타입에 대한 갱신여부를 확인def ismutable(obj) : result = True # 타입을 문자열로 가져오기 com = obj.__class__.__name__ if com not in [ 'int','float','str','tuple'] : result = False return (com,result)# 실행 print 'str is ', ismutable('a')print 'list is',ismutable([])print 'tuple is',ismutable((1,))print 'dict is',ismutable({})print 'object is',ismutable(object)print 'function is',ismutable(lambda x:x)

# 결과값str is ('str', True)list is ('list', False)tuple is ('tuple', True)dict is ('dict', False)object is ('type', False)function is ('function', False)

Page 13: 파이썬정리 20160130

Type Conversion

Page 14: 파이썬정리 20160130

Type conversion 변수에서 참조하는 타입을 자신의 필요한 타입으로 변경이 필요할 경우 사용파이썬에 제공되는 함수들을 이용해서 사용하면 됨

>>> v = 1>>> str(v)'1'>>> float(str(v))1.0>>> int(str(v))1 >>> x = int()>>> x0>>> y = str()>>> y''>>> z = float()>>> z0.0>>>

타입 함수를 이용해서 변수에 할당하면 초기값을 세팅

타입 함수를 이용해서 변수에 적절한 타입으로 변환

Page 15: 파이썬정리 20160130

Type conversion

파라미터를 하나 받아 객체를 실행하면 타입전환 처리함 int() float() str() list() dict() tuple() set()

>>> int<type 'int'>>>> float<type 'float'>>>> str<type 'str'>>>> list<type 'list'>>>> dict<type 'dict'>>>> tuple<type 'tuple'>>>> set<type 'set'>>>>

Page 16: 파이썬정리 20160130

String 에서 integer 변환문자열은 문자와 숫자로 구성될 수 있으므로 숫자여부를 확인하고 형변환을 해야 함

>>> # string 을 내부를 숫자로>>> v = '1‘>>> #string 내장 메소드로 숫자여부 체크>>> if v.isdigit() :... s = int(v)... else :... s = 0... >>> s1

Page 17: 파이썬정리 20160130

Numeric Type

Page 18: 파이썬정리 20160130

숫자타입 숫자에 대한 객체를 관리하는 데이터 타입

Numberic Types

int

float

long

complex

>>> id(1)5939944>>> v = 1>>> type(v)<type 'int'>>>> id(v)5939944>>>

숫자타입도 하나의 객체이므로 1 이 생성되면 동일한 context 내에서는 동일한 객체 id 를 가지고 사용

Page 19: 파이썬정리 20160130

숫자타입 - 기본처리 숫자 타입에 기본으로 처리 되는 함수 , operator

Operation Result Notesx + y sum of x and yx - y difference of x and yx * y product of x and yx / y quotient of x and yx // y (floored) quotient of x and yx % y remainder of x / y

-x x negated+x x unchanged

abs(x) absolute value or magnitude of xint(x) x converted to integer

long(x) x converted to long integerfloat(x) x converted to floating point

complex(re,im) a complex number with real part re, imaginary part im. im defaults to zero.

c.conjugate() conjugate of the complex number cdivmod(x, y) the pair (x // y, x % y)

pow(x, y) x to the power yx ** y x to the power y

Page 20: 파이썬정리 20160130

Sequence Type

Page 21: 파이썬정리 20160130

Sequence 타입 다양한 객체의 값을 원소로 값는 데이터 타입

Sequenec Types

String/unicode

Buffer/range

List/tuple

참조 container

참조참조

값container

** string 일경우 값만 처리

Elements 관리

Page 22: 파이썬정리 20160130

Sequence 타입 - 기본처리 Sequence 타입에 기본으로 처리 되는 함수 , op-erator

Operation Result Notes

x in s True if an item of s is equal to x, else False

x not in s False if an item of s is equal to x, else True

s + t the concatenation of s and t

s * n , n * s n shallow copies of s concatenated

s[i] i'th item of s, origin 0s[i:j] slice of s from i to j

s[i:j:k] slice of s from i to j with step k

len(s) length of smin(s) smallest item of smax(s) largest item of s

Page 23: 파이썬정리 20160130

Sequence-Accessing ValuesSequence Type(String, List, Tuple) 은 변수명 [index] 로 값을 접근하여 가져옴변수에는 Sequence Instance 이 참조를 가지고 있고 index 를 이용하여 값들의 위치를 검색

>>> l = [0,1,2,3]>>> l[0]0>>> s = "string">>> s[0]'s'>>> t = (0,1,2,3)>>> t[0]0>>>

Page 24: 파이썬정리 20160130

Sequence-Updating Values

변수에는 Sequence Instance 이 참조를 가지고 있고 index 를 이용하여 값들의 위치를 검색하고 할당값을 변경 . 단 , Mutable 객체인 List 타입만 기존 값을 변경됨

>>> l[0, 1, 2, 3]>>> l[0] = 100>>> l[100, 1, 2, 3]

>>> t(0, 1, 2, 3)>>> t[0] = 100Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: 'tuple' object does not support item assignment>>>

>>> s'string'>>> >>> s[0] = 'a'Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: 'str' object does not sup-port item assignment

List type Tuple type String type

Page 25: 파이썬정리 20160130

Sequence- 내장함수 이용하기Sequence 내장함수를 이용한 sorted, re-versed, enumerate, zip 을 처리

>>> for i, v in enumerate(['tic', 'tac', 'toe']):... print i, v ... 0 tic1 tac 2 toe

>>> l1 = [1,2,3,4]>>> la = ['a','b','c','d']>>> for k,v in zip(l1,la) :... print k, v... 1 a2 b3 c4 d>>>

>>> for i in reversed(xrange(1,10,2)): ... print i ... 9 7 5 3 1

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> for f in sorted(set(basket)): ... print f... apple banana orange pear

enumerate() zip()

reversed() sorted()

Page 26: 파이썬정리 20160130

Sequence : Slice

Page 27: 파이썬정리 20160130

Sequence slicing Sequence 타입 (string, list, tuple) 에 대한 내부 원소들을 추출하기 위해 slicing 을 사용[ 시작위치 : 종료위치 : 간격 ]

>>> mystring[0:5] 'hello' >>> mystring[6:-1] 'worl'

Page 28: 파이썬정리 20160130

Sequence slicing- 역방향 문자열을 역으로 처리하기

>>> s = 'hello'>>> s[-3:]'llo'>>> s[:-3]'he'>>> s[-1:-3]''>>> s[-1:0]''>>> s[-1:-3:-1]'ol'>>>

역방향으로 처리하기 위해서는 변수명 [ 시작점 : 종료점 : 스텝 ] 정의시 역방향으로 정의하고 스템도 마이너스로 표시하면 역으로 처리

Page 29: 파이썬정리 20160130

Sequence : String Type

Page 30: 파이썬정리 20160130

Sequence-Updating String

String 에 대한 update 는 기본적으로 새로운 String Instance 만드는 것

>>> s'string'>>> id(s)6122176>>> v = "updating " + s>>> id(v)106043176>>> v'updating string'>>> >>> s'string'>>>

Page 31: 파이썬정리 20160130

String-operatorOperator Description Example

+ Concatenation - Adds values on either side of the opera-tor

a + b will give HelloPython

* Repetition - Creates new strings, concatenating multiple copies of the same string

a*2 will give -HelloHello

[] Slice - Gives the character from the given index a[1] will give e

[ : ] Range Slice - Gives the characters from the given range a[1:4] will give ell

in Membership - Returns true if a character exists in the given string

H in a will give 1

not in Membership - Returns true if a character does not exist in the given string

M not in a will give 1

r/R Raw String - Suppresses actual meaning of Escape char-acters. The syntax for raw strings is exactly the same as for normal strings with the exception of the raw string operator, the letter "r," which precedes the quotation marks. The "r" can be lowercase (r) or uppercase (R) and must be placed immediately preceding the first quote mark.

print r'\n' prints \n and print R'\n'prints \n

% Format - Performs String formatting See at next section

Page 32: 파이썬정리 20160130

Sequence-String 메소드 (1)String 내장 메소드

Method Descriptioncapitalize() Capitalizes first letter of string

center(width, fillchar) Returns a space-padded string with the original string centered to a to-tal of width columns.

count(str, beg= 0,end=len(string))

Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given.

decode(encoding='UTF-8',errors='strict')

Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding.

encode(encoding='UTF-8',errors='strict')

Returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with 'ignore' or 'replace'.

endswith(suffix, beg=0, end=len(string))

Determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; returns true if so and false otherwise.

expandtabs(tabsize=8) Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided.

Page 33: 파이썬정리 20160130

Sequence-String 메소드 (2)String 내장 메소드

Method Descriptionfind(str, beg=0

end=len(string))Determine if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise.

index(str, beg=0, end=len(string))

Same as find(), but raises an exception if str not found.

isalnum() Returns true if string has at least 1 character and all characters are al-phanumeric and false otherwise.

isalpha() Returns true if string has at least 1 character and all characters are al-phabetic and false otherwise.

isdigit() Returns true if string contains only digits and false otherwise.

islower() Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.

isnumeric() Returns true if a unicode string contains only numeric characters and false otherwise.

Page 34: 파이썬정리 20160130

Sequence-String 메소드 (3)String 내장 메소드

Method Descriptionisspace() Returns true if string contains only whitespace characters and false

otherwise.istitle() Returns true if string is properly "titlecased" and false otherwise.

isupper() Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.

join(seq) Merges (concatenates) the string representations of elements in se-quence seq into a string, with separator string.

len(string) Returns the length of the string

ljust(width[, fillchar]) Returns a space-padded string with the original string left-justified to a total of width columns.

lower() Converts all uppercase letters in string to lowercase.

lstrip() Removes all leading whitespace in string.

maketrans() Returns a translation table to be used in translate function.

Page 35: 파이썬정리 20160130

Sequence-String 메소드 (4)String 내장 메소드

Method Descriptionmax(str) Returns the max alphabetical character from the string str.

min(str) Returns the min alphabetical character from the string str.

replace(old, new [, max]) Replaces all occurrences of old in string with new or at most max oc-currences if max given.

rfind(str, beg=0,end=len(string))

Same as find(), but search backwards in string.

rindex( str, beg=0, end=len(string))

Same as index(), but search backwards in string.

rjust(width,[, fillchar]) Returns a space-padded string with the original string right-justified to a total of width columns.

rstrip() Removes all trailing whitespace of string.

split(str="", num=string.count(str))

Splits string according to delimiter str (space if not provided) and re-turns list of substrings; split into at most num substrings if given.

splitlines( num=string.count('\n'))

Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed.

Page 36: 파이썬정리 20160130

Sequence-String 메소드 (5)String 내장 메소드

Method Descriptionstartswith(str,

beg=0,end=len(string))Determines if string or a substring of string (if starting index beg and ending index end are given) starts with substring str; returns true if so and false otherwise.

strip([chars]) Performs both lstrip() and rstrip() on string

swapcase() Inverts case for all letters in string.

title() Returns "titlecased" version of string, that is, all words begin with up-percase and the rest are lowercase.

translate(table, deletechars="")

Translates string according to translation table str(256 chars), remov-ing those in the del string.

upper() Converts lowercase letters in string to uppercase.

zfill (width) Returns original string leftpadded with zeros to a total of width charac-ters; intended for numbers, zfill() retains any sign given (less one zero).

isdecimal() Returns true if a unicode string contains only decimal characters and false otherwise.

Page 37: 파이썬정리 20160130

String-escape 문자Backslash notation Hexadecimal character Description

\a 0x07 Bell or alert\b 0x08 Backspace

\000   널문자\cx   Control-x\C-x   Control-x\e 0x1b Escape\f 0x0c Formfeed

\M-\C-x   Meta-Control-x

\n 0x0a Newline 은 라인피드 (Line Feed) 는 커서의 위치를 아랫줄로 이동\nnn   Octal notation, where n is in the range 0.7

\r 0x0d Carriage return 은 현재 위치를 나타내는 커서 를 맨 앞으로 이동\s 0x20 Space\t 0x09 Tab\v 0x0b Vertical tab\x   Character x

\xnn Hexadecimal notation, where n is in the range 0.9, a.f, or A.F

\\ 문자 "\"

\' 단일 인용부호 (')

\" 이중 인용부호 (")

Page 38: 파이썬정리 20160130

Sequence : List Type

Page 39: 파이썬정리 20160130

Sequence - List 기본 처리List 타입에 대한 기본 처리

Python Expression Results Description

l=[1,2,3] l.append(4) [1, 2, 3, 4] 리스트에 원소 추가del l[3] [1, 2, 3] 리스트에 원소 삭제

len([1, 2, 3]) 3 Length 함수로 길이 확인[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] 리스트를 합치니 Concatenation

['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!']

리스트 내의 원소를 Repetition

3 in [1, 2, 3] True 리스트 내의 원소들이 Membership

for x in [1, 2, 3]: print x, 1 2 3 리스트의 원소들을 반복자 활용 - Iteration

Page 40: 파이썬정리 20160130

Sequence-List 용 내장함수내장함수중에 리스트 타입을 처리

Function Descriptioncmp(list1, list2) Compares elements of both lists.

len(list) Gives the total length of the list.

max(list) Returns item from the list with max value.

min(list) Returns item from the list with min value.

list(seq) Converts a tuple into list.

str(list) Produces a printable string representation of a list

type(list) Returns the type of the passed variable. If passed variable is list, then it would return a list type.

Page 41: 파이썬정리 20160130

Sequence-List class 구조 확인 list 는 하나의 class object 로 제공

>>> list<type 'list'>>>> id(list)505560280>>> >>> >>> l1 = list()>>> id(l1)106593376>>> isinstance(l1,list)True>>>

list 의 인스턴스를 생성하고 isinstance 함수를 이용하여 인스턴스 여부 확인

Page 42: 파이썬정리 20160130

Sequence-List 메소드리스트 내장 메소드

Method Descriptionlist.append(obj) Appends object obj to list

list.count(obj) Returns count of how many times obj occurs in list

list.extend(seq) Appends the contents of seq to list

list.index(obj) Returns the lowest index in list that obj appears

list.insert(index,obj) Inserts object obj into list at offset index

list.pop(obj=list[-1]) Removes and returns last object or obj from list

list.remove(obj) Removes object obj from list

list.reverse() Reverses objects of list in place

list.sort([func]) Sorts objects of list, use compare func if given

Page 43: 파이썬정리 20160130

Sequence-List Comprehension

리스트 정의시 값을 정하지 않고 호출 시 리스트 내의 값들이 처리되도록 구성 A = [ 표현식 for i in sequence if 논리식 ]

>>> squares = [] >>> for x in (10): ... squares.append(x**2) ... >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

>>> squares = [x**2 for x in range(10)]>>> squares[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]>>>

Page 44: 파이썬정리 20160130

Sequence-List 로 stack 처리Stack 은 LIFO(last in first out) 으로 List 를 이용하여 원소 추가 (append 메소드 ) 및 삭제 (pop메소드 ) 로 간단하게 구성>>> stack = [3, 4, 5] >>> stack.append(6) >>> stack.append(7) >>> stack [3, 4, 5, 6, 7] >>> stack.pop() 7 >>> stack [3, 4, 5, 6]>>> stack.pop()6 >>> stack.pop()5 >>> stack [3, 4]

Page 45: 파이썬정리 20160130

Sequence-List 로 queue 처리queue 은 FIFO(first in first out) 으로 List 를 이용하여 원소 추가 (append 메소드 ) 및 삭제(reverse,pop 메소드 ) 로 간단하게 구성>>> l = [1,2,3,4]>>> l.reverse()>>> l[4, 3, 2, 1]>>> l.pop()1>>> l.reverse()>>> l[2, 3, 4]>>>

Page 46: 파이썬정리 20160130

Sequence : Tuple Type

Page 47: 파이썬정리 20160130

Sequence - Tuple 기본 처리tuple 타입에 immutable 타입으로 내부 원소에 대해 갱신이 불가능하여 리스트처리보다 제한적Slicing 은 String 처럼 처리가능

Python Expression Results Description

T =(1,) (1,) 튜플의 원소가 하나인 경우 생성 꼭 한 개일 경우는 뒤에 꼼마 (,) 를 붙여야 함

T = (1,2,3,4) (1, 2, 3, 4) 튜플 생성len((1, 2, 3)) 3 Length 함수로 길이 확인

(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) 튜플을 합치기 Concatenation

('Hi!‘) * 4 'Hi!Hi!Hi!Hi!' 튜플의 반복을 string 으로 표시 3 in (1, 2, 3) True 튜플 내의 원소들이 Membership

for x in (1, 2, 3): print x, 1 2 3 튜플의 원소들을 반복자 활용 - Iteration

Page 48: 파이썬정리 20160130

Sequence- Tuple 용 내장함수내장함수 중에 tuple 타입을 처리

Function Descriptioncmp(tuple1, tuple2) Compares elements of both tuples.

len(tuple) Gives the total length of the tuple.

max(tuple) Returns item from the tuple with max value.

min(tuple) Returns item from the tuple with min value.

tuple(seq) Converts a list into a tuple.

str(tuple) Produces a printable string representation of a tuple

type(tuple) Returns the type of the passed variable. If passed variable is tuple, then it would return a tuple type.

Page 49: 파이썬정리 20160130

Set Type

Page 50: 파이썬정리 20160130

Set 타입중복을 허용하지 않고 , 순서가 없음 (unordered)교집합 (&), 합집합 (|), 차집합 (-) 연산 처리Set: mutable setFrozenset: immutable set

Page 51: 파이썬정리 20160130

Set 타입 – 생성시 주의Set() 으로 생성시 파라미터는 1 개만 받는다 . 리스트 등 muta-ble 객체를 요소로 처리할 수 없다 . 그래서 튜플로 처리

>>> s = set([1],[2])Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: set expected at most 1 arguments, got 2>>> s = set(([1],[2]))Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: unhashable type: 'list'>>> >>> s = set(((1),(2)))>>> sset([1, 2])>>> >>> s = set({'a':1})>>> sset(['a'])

Set 은 구조상 내부 요소가 변경이 가능한 값으로 구성할 수 없다

Set 에 dictionary 로 생성시 요소는 변경할 수 없는 immutable 타입만 생성함

Page 52: 파이썬정리 20160130

Set 타입 – Set 생성 및 추가Set type 은 mutable 타입이므로 생성 후 원소를 추가나 삭제가 가능

>>> >>> s = set([1,2,3])>>> sset([1, 2, 3])>>> s1 = set([1,2,3,3,4,4])>>> s1set([1, 2, 3, 4])>>> s.add(5)>>> sset([1, 2, 3, 5])>>> s1.add(5)>>> s1set([1, 2, 3, 4, 5])>>>

Page 53: 파이썬정리 20160130

Set 타입 – FrozenSet 생성 및 추가FrozenSet type 은 immutable 타입이므로 생성 후 원소를 추가나 삭제가 불가능

>>> s = frozenset([1,2,3])>>> sfrozenset([1, 2, 3])>>> s.add(4)Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: 'frozenset' object has no attribute 'add'>>>

Page 54: 파이썬정리 20160130

Set 타입 - 기본처리Operation Equivalent Result

len(s) cardinality of set s

x in s test x for membership in s

x not in s test x for non-membership in s

s.issubset(t) s <= t test whether every element in s is in t

s.issuperset(t) s >= t test whether every element in t is in s

s.union(t) s | t new set with elements from both s and t

s.intersection(t) s & t new set with elements common to s and t

s.difference(t) s - t new set with elements in s but not in t

s.symmetric_difference(t) s ^ t new set with elements in either s or t but not both

s.copy() new set with a shallow copy of s

Page 55: 파이썬정리 20160130

Set 타입 - set 확장처리Operation Equivalent Results.update(t) s |= t update set s, adding elements from t

s.intersection_update(t) s &= t update set s, keeping only elements found in both s and t

s.difference_update(t) s -= t update set s, removing elements found in t

s.symmetric_difference_update(t) s ^= t update set s, keeping only elements found in ei-

ther s or t but not in both

s.add(x) add element x to set s

s.remove(x) remove x from set s; raises KeyError if not present

s.discard(x) removes x from set s if present

s.pop() remove and return an arbitrary element from s; raises KeyError if empty

s.clear() remove all elements from set s

Page 56: 파이썬정리 20160130

Map Type

Page 57: 파이썬정리 20160130

Map 타입 -dictionary

Key/Value 로 원소를 관리하는 데이터 타입 요소들은 변경가능하므로 변수에 복사시

참조 container

Name 1 값

Name 2

con-tainer

참조

참조

:

:

Dictionary Type

Page 58: 파이썬정리 20160130

Map 타입 - Accessing Elements

Key/Value 로 원소를 관리하므로 Key 를 가지고 원소를 검색

>>> dd = {'name': 'dahl', 'age':50}>>> dd{'age': 50, 'name': 'dahl'}>>> dd['name']'dahl'>>>

Page 59: 파이썬정리 20160130

Map 타입 - Updating Elements

Dictionary 타입에 새로운 key 에 할당하면 새로운 것을 추가하고 기존 key 로 검색하여 값을 변경하면 기존 값을 변경함>>> dd = {'name': 'dahl', 'age':50}>>> dd{'age': 50, 'name': 'dahl'}>>> dd['name']'dahl'>>>>>> dd['sex'] ='male'>>> dd{'age': 50, 'name': 'dahl', 'sex': 'male'}>>> >>> dd['name'] = 'dahl moon'>>> dd{'age': 50, 'name': 'dahl moon', 'sex': 'male'}>>>

새로운 key 에 할당 : 기존에 없으므로 추가

기존 key 에 할당 : 기존에 있는 값을 변경

Page 60: 파이썬정리 20160130

Map 타입 - Delete Elements

Dictionary 타입에 원소 하나만 삭제 , 원소들을 삭제 , dictionary instance 삭제 >>> dd{'age': 50, 'name': 'dahl moon', 'sex': 'male'}>>> del dd['sex']>>> dd{'age': 50, 'name': 'dahl moon'}>>> >>> dd.clear()>>> dd{}>>> del dd>>> ddTraceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'dd' is not defined>>>

기존 원소 하나 삭제

Dict 삭제

모든 원소 삭제

Page 61: 파이썬정리 20160130

Map 타입 – dict 지원 내장함수 Dictionary 타입에 원소 하나만 삭제 , 원소들을 삭제 , dictionary instance 삭제

Function Descriptioncmp(dict1, dict2) Compares elements of both dict.

len(dict) Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.

str(dict) Produces a printable string representation of a dictionary

type(dict) Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type.

dict(mapping) Converts a map into list.

Page 62: 파이썬정리 20160130

Map 타입 -dict class 구조 확인 dict 는 하나의 class object 로 제공

>>> dict<type 'dict'>>>> id(dict)505532280>>>>>> d1 = dict()>>> id(d1)105140272>>> isinstance(d1,dict)True>>>

Dict 의 인스턴스를 생성하고 isinstance 함수를 이용하여 인스턴스 여부 확인

Page 63: 파이썬정리 20160130

Map 타입 -dictionary 메소드 내장 메소드

Method Descriptiondict.clear() Removes all elements of dictionary dict

dict.copy() Returns a shallow copy of dictionary dict

dict.fromkeys() Create a new dictionary with keys from seq and values set to value.

dict.get(key, default=None)

For key key, returns value or default if key not in dictionary

dict.has_key(key) Returns true if key in dictionary dict, false otherwise

dict.items() Returns a list of dict's (key, value) tuple pairs

dict.keys() Returns list of dictionary dict's keys

dict.setdefault(key, de-fault=None)

Similar to get(), but will set dict[key]=default if key is not already in dict

dict.update(dict2) Adds dictionary dict2's key-values pairs to dict

dict.values() Returns list of dictionary dict's values

Page 64: 파이썬정리 20160130

Boolean type & None

Page 65: 파이썬정리 20160130

Boolean 타입 파이썬은 true/false 를 실제 값이 존재하거나 없는 경우에 조건식을 확정할 경우 사용

값 참 or 거짓"python" 참

"" 거짓[1, 2, 3] 참

[] 거짓() 거짓{} 거짓1 참0 거짓

None 거짓

If 조건식 : passElse : pass

조건식에 값들이 참과 거짓을 구별하여 처리

Page 66: 파이썬정리 20160130

None

정의된 것이 없는 타입을 세팅할 때 표시 존재하지 않음 (Not Exists) 정의되지 않음 (Not Assigned, Not Defined) 값이 없음 (No Value) 초기값 (Initialized Value)

Page 67: 파이썬정리 20160130

STRING FORMAT

Page 68: 파이썬정리 20160130

String Format – 메소드 ( 권장 )

Page 69: 파이썬정리 20160130

String-format 함수 – index 치환 “ { 파라미터 위치 } “.format( 파라미터 ) 파라미터 위치는 0 부터 시작 증가

>>> " {0} {1} ".format(1,2,3)' 1 2 '>>> " {0} {1} {2} {3} ".format(1,2,3)Traceback (most recent call last): File "<stdin>", line 1, in <module>IndexError: tuple index out of range>>>

{} 개수가 파라미터보다 작으면 처리가 되지만 {] 개수가 파라미터 개수보다 많으면 오류가 발생

Page 70: 파이썬정리 20160130

String-format 함수 – name 치환 “ { 파라미터 변수명 } “.format( 변수명 =값 ,)

>>> "{first} {second} ".format(first=1, sec-ond=2)'1 2 '>>>

{} 개수가 파라미터보다 작으면 처리가 되지만 {] 개수가 파라미터 개수보다 많으면 오류가 발생

Page 71: 파이썬정리 20160130

String-format 함수 – 혼용 치환 “ { 위치 } { 파라미터 변수명 } “.format( 값 , 변수명 = 값 )

>>> "{0} {second} ".format(1, second=2)'1 2 '>>>

파라미터 처리시 Key/Value 처리는 맨 뒷에서 처리가 되어야 함

Page 72: 파이썬정리 20160130

String-format 메소드 – 정렬 “ { 위치 : [ 공백부호 ][ 정렬방법부호 ] 정렬될 공간 } “.format( 파라미터 ) < : 좌측 정렬 >: 우측정력 ^: 가운데 정렬

>>> " left: {0:<10} right:{1:>10} centre:{2:^10} ".format('hi', 'world', '!')' left: hi right: world centre: ! '>>>

>>> "{0:=^10}".format("hi") '====hi====' >>> "{0:!<10}".format("hi") 'hi!!!!!!!!'

공백을 채우려면 정렬방법부호 앞에 공백으로 대체할 문자를 표시하면 된다 .

Page 73: 파이썬정리 20160130

String Format -%

Page 74: 파이썬정리 20160130

String-format 처리 (%) 문자열 내에 특정 값들을 재정의하는 방법 “ 스트링 “ % ( 스트링 내부 매칭 값 )

text = "%d little pigs come out or I'll %s and %s and %s" % (3, 'huff', 'puff', 'blow down')

Page 75: 파이썬정리 20160130

String-format 코드 문자열 내에 특정 값들을 재정의하는 방법 “ 스트링 “ % ( 스트링 내부 매칭 값 )

코드 설명%s 문자열 (String)%c 문자 한개 (character)%d 정수 (Integer)%f 부동소수 (floating-point)%o 8 진수%x 16 진수%% Literal % ( 문자 %  자체 )

Page 76: 파이썬정리 20160130

String-format 정렬 방식 %( 부호 ) 숫자 (. 숫자 )?[s|d|f] + 부호는 우측정렬 / - 부호는 좌측 정렬

>>> v = 10>>> " a %10d a " % v ' a 10 a '>>> " a %-10d a " % v ' a 10 a '>>>

Page 77: 파이썬정리 20160130

OPERATOR

Page 78: 파이썬정리 20160130

내장 메소드와 연산자 파이썬은 연산자에 상응하는 내장메소드를 가지고 있어 각 타입별로 연산자에 상응한 내장메소드가 구현되어 있음

>>> 1+12>>> p=1>>> p.__add__(1)2>>> >>> "Hello" + "World"'HelloWorld'>>> "Hello".__add__("World")'HelloWorld'>>>

int 타입이나 str 타입 일 경우 + 연산자와 __add__() 메소드는 동일하게 처리됨

Page 79: 파이썬정리 20160130

사칙연산자Operator Description Example

+Addition

Adds values on either side of the operator. a + b = 30

- Subtraction

Subtracts right hand operand from left hand op-erand.

a – b = -10

* Multiplication

Multiplies values on either side of the operator a * b = 200

/ Division

Divides left hand operand by right hand operand b / a = 2

% Modulus

Divides left hand operand by right hand operand and returns remainder

b % a = 0

** Exponent

Performs exponential (power) calculation on op-erators

a**b =10 to the power 20

// Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed.

9//2 = 4 and 9.0//2.0 = 4.0

Page 80: 파이썬정리 20160130

비교연산자Operator Description Example

== If the values of two operands are equal, then the condition becomes true.

(a == b) is not true.

!= If values of two operands are not equal, then condition becomes true.

<> If values of two operands are not equal, then condition becomes true.

(a <> b) is true. This is similar to != operator.

> If the value of left operand is greater than the value of right operand, then condition becomes true.

(a > b) is not true.

< If the value of left operand is less than the value of right operand, then condition becomes true.

(a < b) is true.

>= If the value of left operand is greater than or equal to the value of right operand, then condi-tion becomes true.

(a >= b) is not true.

<= If the value of left operand is less than or equal to the value of right operand, then condition be-comes true.

(a <= b) is true.

Page 81: 파이썬정리 20160130

할당연산자Operator Description Example

= Assigns values from right side operands to left side operand

c = a + b assigns value of a + b into c

+= Add AND

It adds right operand to the left operand and assign the result to left operand

c += a is equivalent to c = c + a

-= Subtract AND

It subtracts right operand from the left operand and assign the result to left operand

c -= a is equivalent to c = c - a

*= Multiply AND

It multiplies right operand with the left operand and assign the result to left operand

c *= a is equivalent to c = c * a

/= Divide AND

It divides left operand with the right operand and assign the result to left operand

c /= a is equivalent to c = c / ac /= a is equivalent to c = c / a

%= Modulus AND

It takes modulus using two operands and assign the result to left operand

c %= a is equivalent to c = c % a

**= Exponent AND

Performs exponential (power) calculation on operators and assign value to the left operand

c **= a is equivalent to c = c ** a

//= Floor Division

It performs floor division on operators and as-sign value to the left operand

c //= a is equivalent to c = c // a

Page 82: 파이썬정리 20160130

비트연산자Operator Description Example

& Binary AND

Operator copies a bit to the result if it ex-ists in both operands

(a & b) (means 0000 1100)

| Binary OR

It copies a bit if it exists in either operand. (a | b) = 61 (means 0011 1101)

^ Binary XOR

It copies the bit if it is set in one operand but not both.

(a ^ b) = 49 (means 0011 0001)

~ Binary Ones Complement

It is unary and has the effect of 'flipping' bits.

(~a ) = -61 (means 1100 0011 in 2's complement form due to a signed binary number.

<< Binary Left Shift

The left operands value is moved left by the number of bits specified by the right operand.

a << = 240 (means 1111 0000)

>> Binary Right

Shift

The left operands value is moved right by the number of bits specified by the right operand.

a >> = 15 (means 0000 1111)

Page 83: 파이썬정리 20160130

논리연산자Operator Description Example

and Logical AND

If both the operands are true then condition becomes true.

(a and b) is true.

or Logical OR

If any of the two operands are non-zero then condition becomes true.

(a or b) is true.

not Logical NOT

Used to reverse the logical state of its operand.

Not(a and b) is false.

Page 84: 파이썬정리 20160130

논리연산자 - 단축연산

Operator Description Example&Logical AND

첫번째 조건이 참일 경우 두번째 조건 결과 전달첫번째 조건이 거짓일 경우 첫번째 조건 결과 전달

>>>s ='abc' >>>(len(s) == 3) & s.isalpha()True>>> (len(s) == 4) & s.isalpha()False>>>

|Logical OR

첫번째 조건이 참일 경우 첫번째 조건 결과 전달첫번째 조건이 거짓일 경우 두번째 조건 결과 전달

>>> (len(s) == 3) | s.isdigit()True

>>> (len(s) == 4) | s.isdigit()False>>>

논리 연산 중에 단축연산이 필요한 경우에 사용하고 두 조건을 전체를 비교할 경우는 기본 논리연산자를 사용해야 함

Page 85: 파이썬정리 20160130

논리연산자 – 단축연산 예시&, | 연산을 비교시 축약형 처리하는데 결과를 리턴함& : 좌측이 참이면 우측을 리턴| : 좌측이 거짓이면 우측을 리턴

>>> (10+1) & 00>>> (10+1) | 011>>> 0 |1010>>>

Page 86: 파이썬정리 20160130

멤버쉽 연산자Operator Description Example

in Evaluates to true if it finds a variable in the specified sequence and false otherwise.

x in y, here in results in a 1 if x is a member of sequence y.

not in Evaluates to true if it does not finds a vari-able in the specified sequence and false oth-erwise.

x not in y, here not in results in a 1 if x is not a member of sequence y.

Page 87: 파이썬정리 20160130

식별 연산자Operator Description Example

is Evaluates to true if the variables on ei-ther side of the operator point to the same object and false otherwise.

x is y, here is results in 1 if id(x) equals id(y).

is not Evaluates to false if the variables on ei-ther side of the operator point to the same object and true otherwise.

x is not y, here is not results in 1 if id(x) is not 

Page 88: 파이썬정리 20160130

연산자 우선순위Operator Description

** Exponentiation (raise to the power)

~ + - Ccomplement, unary plus and minus (method names for the last two are +@ and -@)

* / % // Multiply, divide, modulo and floor division

+ - Addition and subtraction

>> << Right and left bitwise shift

& Bitwise 'AND'^ | Bitwise exclusive `OR' and regular `OR'

<= < > >= Comparison operators<> == != Equality operators

= %= /= //= -= += *= **= Assignment operators

is is not Identity operatorsin not in Membership operators

not or and Logical operators

Page 89: 파이썬정리 20160130

PYTHON파싱 처리 기준

Page 90: 파이썬정리 20160130

식별자

Page 91: 파이썬정리 20160130

식별자 란 식별자는 이름공간에서 별도로 구별할 수 있는 이름 정의식별자 대상 : 변수 , 함수 , 객체 , 모듈 , 패키지 등등파이썬은 이름으로 식별하기 때문에 동일한 이름이 만들어지면 재할당됨

Page 92: 파이썬정리 20160130

식별자 처리 원칙 클래스 이름은 대문자로 시작 클래스 이름 이외는 소문자로 시작 하나의 밑줄과 식별자를 시작하면 Private 두 개의 주요 밑줄 식별자를 시작하면 강력한 Pri-

vate 앞뒤로 두개의 밑줄로 끝나는 경우 , 언어 정의 특별한 이름으로 사용

Page 93: 파이썬정리 20160130

문장 구분 멀티라인 (\) : 여러 문장을 하나로 처리 블록 구분 : intention 으로 구분 라인 구분 : 개행문자 (\n) 를 기준으로 구분 주석 (#) : 파이썬 문장과 구분한 설명 Doc 설명 : single ('), double (") and triple

(''' or """) quotes 를 프로그램 맨 앞에 넣으면 모듈명 .__doc__ 로 검색가능 한문장으로 그룹화 (;) : 여러문장을 ; 로 연결해서 한 문장으로 만들 수 있음

Page 94: 파이썬정리 20160130

문장 구분 - doc 처리 모듈 내부에 모듈에 대한 설명이 필요할 경우 넣는 법

>>> import doctesthello world >>> doctest.__doc__'\nCreated on Fri Jan 08 14:46:31 2016\n\n@au-thor: 06411\n'>>>

# doctest.py # -*- coding: utf-8 -*-"""Created on Fri Jan 08 14:46:31 2016

@author: 06411"""

print("hello world ")

모듈 처리모듈 작성

Page 95: 파이썬정리 20160130

Variable

Page 96: 파이썬정리 20160130

변수 (Variable) 변수는 객체를 관리하기 위한 참조를 관리하는 공간 즉 , 변수는 객체를 가리키는 것

변수 내의 값 수치값 문자열

컨테이너함수

클래스

튜플리스트

딕션너리

집합변수 Variable

객체의 참조 즉 , 주소 저장

Variable 정의 = 값 할당 리터럴 ( 객체 )

Page 97: 파이썬정리 20160130

Variable 정의 및 할당변수 정의는 값과 binding( 할당 ) 될 때 정의변수 정의 없이 사용되면 에러가 발생Scope 원칙에 따라 동일한 이름이 발생시는 변수 내에 저장된 것을 변경

I + 1 에서 I 를 검색I 변수에 값이 할당되기 이전에 즉 이름공간에 생성되기 전이므로 “ NameError: name 'i' is not defined “ 에러가 발생

변수 정의 없이 할당I = I + 1

>>> message = "What's up, Doc?">>> n = 17>>> pi = 3.14159

변수 정의 ( 할당 )

할당 연산자를 이용하여 값을 변수에 할당 .실제 값의 참조가 변수에 보관

Page 98: 파이썬정리 20160130

Assignment & Type infer-ence

파이썬 언어는 동적 타입을 체크하므로 주어진 타입을 추정해서 처리

I = 1l = “string”l = 1.1

l 은 변수이지만 변수 정의와 변수할당이 동시에 된다 .변수에 할당시 타입을 추정해서 동적으로 정해진다 .

파이썬에서 연속적으로 할당시 변수에 저장된 타입이 변경된다 .

Page 99: 파이썬정리 20160130

Variable 삭제Context 내에서 변수 삭제 .del 변수명 , del( 변수명 ) 으로 삭제

>>> a= 1>>> b =1>>> a1>>> b1>>> del a>>> del(b)>>> aTraceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'a' is not defined>>> bTraceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'b' is not defined>>>

Page 100: 파이썬정리 20160130

Building Block

Page 101: 파이썬정리 20160130

Building block Expression Function Object Variable : point to object Command

Page 102: 파이썬정리 20160130

ExpressionAn expression is a combination of values, variables, and op-erators.표현식을 선언해도 실제 정의되는 것이 객체이므로 별도의 블록이 유지 됨

>>> (i for i in l)<generator object <genexpr> at 0x06521E68>>>> dir((i for i in l))['__class__', '__delattr__', '__doc__', '__format__', '__ge-tattribute__', '__hash__', '__init__', '__iter__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'gi_code', 'gi_frame', 'gi_running', 'next', 'send', 'throw']>>>

Page 103: 파이썬정리 20160130

지역변수와 전역변수동적 데이터 타입 : 변수에 값이 할당될 경우 데이터 타입이 확정됨변수는 이름공간 내에서 관리되면 변수는 동적으로 할당이 가능하다 .변수 검색 기준은 Local > Global > Built-in 영역 순으로 찾는다Locals() 와 globals() 함수를 이용해서 검색

>>> p = 100>>> >>> def add(x,y) :… p =0… print(locals())>>> globals()>>>

함수내 파라미터와 그 내부에 정의된 변수

함수 외부 변수는 전역변수

Page 104: 파이썬정리 20160130

Variable Bound/unbound변수는 할당될 때 Binding 됨

>>> i =0>>> i = i + 1>>> i1

>>>I = I + 1Traceback (most recent call last): File "<stdin>", line 1, in <mod-ule>NameError: name 'i' is not de-fined

어휘분석에 따른 할당 될 경우 I + 1 부터 처리시 Unbinding 에러가 발생함 (NameEr-ror: name 'i' is not defined)

Page 105: 파이썬정리 20160130

Namespace

Page 106: 파이썬정리 20160130

Namespace 파이썬은 모듈 , 패키지 , 프로젝트 등의 단위로 작업공간을 두고 name 을 기준으로 식별한다 .

모듈 , 패키지 , 프로젝트 단위로 동일한 name 을 가진 변수 , 클래스 객체 , 함수 , 값 객체 등을 관리해서 이중으로 발생하지 않도록 처리

Page 107: 파이썬정리 20160130

Namespace 관리 기준Import 로 패키지를 포함한 모듈을 호출하여 모듈처리 시 식별이 명확하도록 작업공간을 분리프로젝트는 pythonpath 를 기준으로 관리해서 로드한다 .

공통 기능은 별도의 모듈로 분리해서 프로젝트를 분리해서 사용해야 이름공간이 충돌을 방지할 수 있다모든 객체이므로 이름공간관리

프로젝트패키지

패키지모듈

함수클래스

Page 108: 파이썬정리 20160130

Namespace 확인하기Dir() 함수 : 패키지 , 모듈 등 네임스페이스 관리를 List 로 표시

__dict__ : 객체 네임스페이스를 관리 사전으로 표시>>>dir() >>>dir( 패키지 )

>>> 객체이름 .__dict__>>>

Page 109: 파이썬정리 20160130

Object Namespace 흐름Base class

class

in-stance

in-stance

in-stance

상속

인스턴스 생성

Dict{}

Dict{}

Dict{} Dict{} Dict{}

Namespace 검색

객체는 자신들이 관리하는 Namespace 공간을 생성하며 객체 내의 속성이나 메소드 호출시 이를 검색해서 처리

Page 110: 파이썬정리 20160130

function Namespace 흐름

Namespace 검색

함수는 내부의 로직 처리를 위한 Names-pace 를 별도로 관리한다 .

내부함수가 실행되면 외부함수 Namespace를 참조하여 처리할 수 있다 .

하위에서 상위는 참조가 가능하나 상위에서 하위는 참조가 불가함수 내부에서 locals()/globals() 관리 영역 참조가능

모듈

외부함수

내부함수 내부함수 내부함수

영역 참조

영역참조

Dict{}

Dict{}

Dict{} Dict{} Dict{}

Built-in Dict{}

영역 참조

Page 111: 파이썬정리 20160130

Namespace 기준 프로젝트 패키지 모듈 함수 클래스 / 인스턴스 객체 - 클래스 객체는 클래스 멤버들에 대한 관리할 경우에만 이름공간 역할을 수행

Page 112: 파이썬정리 20160130

Control flow

Page 113: 파이썬정리 20160130

Statement

Statement Description

if statements 조건식 결과가 true 일 경우만 처리if...else statements 조건식 결과가 true 일 경우는 if 내의

블럭처리하고 false 일 경우 else 내의 블록 처리

nested if statements If 와 elif 조건식 결과가 true 일 경우 블럭처리하고 모든 조건식이 false 일 경우 else 블럭처리

Page 114: 파이썬정리 20160130

For Statement파이썬에서는 for in (sequence 타입 ) 으로 처리함For 문을 처리하고 추가적으로 처리할 것이 필요하면 else 구문을 이용하여 처리함

Page 115: 파이썬정리 20160130

Loop Statement

Loop Type Description

while loop 조건식이 true 일 경우에 실행for loop sequence 타입에 대해 순환하여 처리nested loops 순환내에 내부적인 순환조건을 만들 경우 외부

순환에 맞춰 내부 순환이 반복하여 실행

Page 116: 파이썬정리 20160130

With Statement파이썬에서 with 문은 파일 , 락 등 오픈하면 닫아야 하는 것을 자동으로 처리하는 환경을 만들어줌

f = open("foo.txt", 'w')f.write("Life is too short, you need python")f.close()

with open("foo.txt", "w") as f: f.write("Life is too short, you need python")

With 구문을 사용하는 경우 file close 문을 사용하지 않아도 처리가 끝나면 클로즈가 자동으로 됨

Page 117: 파이썬정리 20160130

Break Statement기존 control flow 를 강제로 빠져나갈 경우 필요

for x in range(0, 5):    print(x)    if(x == 6):        breakelse:    print("else")

Page 118: 파이썬정리 20160130

Continue Statement기존 control flow 를 처리시 조건이 맞을 경우 처음으로 돌아가서 계속 실행할 수 있도록 처리

>>> for i in [1,2,3,4,5] :... if i == 2 :... continue... print i... 1345

Page 119: 파이썬정리 20160130

Pass Statement처리가 필요없는 블록이 필요할 경우 pass 문을 사용하여 처리하지 않음Continue 문장과의 차이점은 pass 문은 현재 실행이 없다는 것을 의미만 함

>>> for i in [1,2,3,4,5] :... if i == 2 :... pass... print i... 12345

Page 120: 파이썬정리 20160130

else StatementFor/while 문 등 반드시 처리가 필요한 경우 else문을 이용하여 처리 .If than else 는 하나의 구문이므로 else 문과는 구분해야 함

>>> if [1]: ... print("Then")... else: ... print("Else") Then >>>>>> for x in [1]: ... print("Then") ... else: ... print("Else") ... Then Else

Page 121: 파이썬정리 20160130

Module/package

Page 122: 파이썬정리 20160130

모듈모듈이란 함수나 변수들 , 또는 클래스들을 모아놓은 파일파이썬이 모듈은 하나의 객체이면서 하나의 이름공간을 구성해서 내부 속성에 대한 처리 방안을 제시한다 .

모듈 내의 속성에 대한 접근은 점 (.) 연산자를 통해 접근

# 모듈 mod.py

def apple(): print "I AM APPLES!" # this is just a variable

tangerine = "Living reflection of a dream"

# 모듈 mod_import.py

import modmod.apple() print mod.tangerine"

Page 123: 파이썬정리 20160130

모듈 namespace 검색하기모듈도 객체이므로 하나의 이름공간을 관리한다 .

Namespace : 모듈명 .__dict__ 모듈 내의 속성을 가져오기 : 모듈명 .__dict__.get(‘ 속성명’ )

# 모듈 mod.py

def apple(): print "I AM APPLES!" # this is just a variable

tangerine = "Living reflection of a dream"

# 모듈 mod_import.py

import mod

mod.__dict__.get(‘apple’) mod.__dict__.get(‘tangerine ’)

Page 124: 파이썬정리 20160130

모듈 namespace 검색하기모듈도 객체이므로 하나의 이름공간을 관리한다 .

Namespace : 모듈명 .__dict__ 모듈 내의 속성을 가져오기 : 모듈명 .__dict__.get(‘ 속성명’ )

# 모듈 mod.py

def apple(): print "I AM APPLES!" # this is just a variable

tangerine = "Living reflection of a dream"

# 모듈 mod_import.py

import mod

mod.__dict__.get(‘apple’) mod.__dict__.get(‘tangerine ’)

Page 125: 파이썬정리 20160130

if __name__ == "__main__":

Command 창에서 모듈을 호출할 경우 __name__ 속성에 “ __main__” 으로 들어감Command 창에서 실행하면 현재 호출된 모듈을 기준으로 실행환경이 설정되기 때문에 “ __main__” 이 실행환경이 기준이 됨

Page 126: 파이썬정리 20160130

command line 모듈 실행직접 모듈 호출할 경우 __name__ 의 값이 모듈명이 아닌 __main__ 으로 처리실제 모듈에서 호출된 것과 import 되어 활용하는 부분을 별도로 구현이 가능if __name__ == "__main__": # 직접 모듈 호출시 실행되는 영역 print(safe_sum('a', 1)) print(safe_sum(1, 4)) print(sum(10, 10.4))else : # import 시 실행되는 영역

Page 127: 파이썬정리 20160130

모듈 – import 처리 예시

# 현재 디렉토리 c:\python# mod1.py def sum(a, b): return a + b

c:\python>dir ... 2014-09-23 오후 01:53 49 mod1.py ...

# 현재 디렉토리 c:\python# 다른 모듈에서 호출시import mod1

mod1.sum(10,10) # 결과값 20 실행

모듈을 현재 작성되는 모듈에서 호출하려면 import 해야 하며 실행되는 환경도 호출하는 모듈을 기준으로 만들어진다 .

Module 정의 Module import

Page 128: 파이썬정리 20160130

패키지패키지 (Packages) 는 도트 ('.') 를 이용하여 파이썬 모듈을 계층적 ( 디렉토리 구조 ) 으로 관리절대경로import game.sound.echo # 패키지 . 패키지 . 모듈 from game.sound import echofrom game.sound.echo import echo_test # 패키지 . 패키지 . 모듈 한 후 모듈속성 정의상대경로import .echo # 현재 패키지에 모듈을 importimport ..echo # 상위 패키지에 모듈 import

game/ __init__.py # 패키지에 반드시 생성해야 함 sound/ __init__.py echo.py wav.py graphic/ __init__.py screen.py render.py play/ __init__.py run.py test.py

Page 129: 파이썬정리 20160130

패키지 예시 (1)1. Kakao 프로젝트는 pythonpath 에 등록2. account 패키지 생성3. account 패키지 내에 account.py 생성

Page 130: 파이썬정리 20160130

패키지 예시 (2)1. myproject 프로젝트는 pythonpath 에 등록2. add_test.py 생성3. account.account 를 import 하여

Page 131: 파이썬정리 20160130

모듈 :pythonpath 등록모듈에 대한 검색에서 오류가 발생할 경우 pythonpath 에 현재 디렉토리 위치를 추가해야 함set PYTHONPATH=c:\python20\lib;

Page 132: 파이썬정리 20160130

모듈 : ide 에서 path 등록실제 다양한 패키지를 사용할 경우 각 패키지를 등록해야 한다 .

#path>>> import sys>>> sys.path ['', 'C:\\Windows\\SYSTEM32\\python34.zip', 'c:\\Python34\\DLLs', 'c:\\Python34\\lib', 'c:\\Python34', 'c:\\Python34\\lib\\site-packages']

# 현재 작성된 모듈의 위치 등록>>> sys.path.append("C:/Python/Mymodules") >>> sys.path ['', 'C:\\Windows\\SYSTEM32\\python34.zip', 'c:\\Python34\\DLLs', 'c:\\Python34\\lib', 'c:\\Python34', 'c:\\Python34\\lib\\site-packages', 'C:/Python/Mymodules'] >>>

>>> import mod2 >>> print(mod2.sum(3,4)) # 결과값 7

Page 133: 파이썬정리 20160130

FUNCTION

Page 134: 파이썬정리 20160130

Function 기초

Page 135: 파이썬정리 20160130

함수 함수 정의와 함수 실행으로 구분함수를 실행 ( 호출 ) 하기 전에 모듈 내에 함수 정의를 해야 함# 함수 정의def 함수명 ( 인자 ) 구문블럭 (:) 함수 내부 로직# 함수 실행함수명 ( 인자 )

함수 객체함수인자객체

함수 명( 참조 )

Page 136: 파이썬정리 20160130

함수 내부 구조 알아보기함수가 정의되면 함수 코드도 하나의 객체로 만들어짐간단히 함수에 대한 로컬변수 확인해 봄

>>> def add(x,y) :... return x+y... >>> # 함수정의에 대한 내부 구조>>> add.func_code.co_varnames('x', 'y')>>> >>> # 함수코드는 bytecode 로 나타남>>> add.func_code.co_code'|\x00\x00|\x01\x00\x17S'>>>

Page 137: 파이썬정리 20160130

함수 – 메모리 생성 규칙 함수 호출 시 마다 Stack 에 함수 영역을 구성하고 실행됨 함수를 재귀호출할 경우 각 호출된 함수 별로 stack영역을 구성하고 처리

함수정의함수호출 1

함수호출 2

함수호출 3

함수호출 4

Stack

제일 마지막 호출된 것을 처리가 끝나면 그 전 호출한 함수를 처리load

Page 138: 파이썬정리 20160130

함수 – 메모리 생성 예시 정의된 함수에서 실제 함수를 실행시 함수 인스턴스를 만들어서 실행됨

funcs = []for i in range(4): def f(): print I

# 함수 인스턴스를 추가 funcs.append(f)

print funcs

i =0for f in funcs: i += 1 print id(f), f()

[<function f at 0x02C1CF30>, <function f at 0x02C29EF0>, <function f at 0x02C29FB0>, <function f at 0x02C37370>]

46255920 1None46309104 2None46309296 3None46363504 4None

함수 생성된 개수만큼 생성됨

레퍼런스를 정수로 변환처리

Page 139: 파이썬정리 20160130

함수 변수 Scoping함수에 실행하면 함수 내의 변수에 대한 검색을 처리 .검색 순은 Local > global > Built-in 순으로 호출Global/nonlocal 키워드를 변수에 정의해서 직접 상위 영역을 직접 참조할 수 있다

globalBuilt-in

함수 Scope

함수 Namespace

local 내부함수local

Page 140: 파이썬정리 20160130

함수 -Namespace 함수내의 인자를 함수 이름공간으로 관리하므로 하나의 dictionary 로 관리 함수 인자는 이름공간에 하나의 키 / 값 체계로 관리 함수의 인자나 함수내의 로컬변수는 동일한 이름공간에서 관리 locals() 함수로 함수 내의 이름공간을 확인할 수 있음#

Page 141: 파이썬정리 20160130

함수 -Namespace : locals() 함수의 이름공간 locals() 함수를 이용하여 확인하기함수명 .__globals__ 나 globals() 함수를 호출하여 글로벌 context 내의 이름공간을 확인

>>> def add(x,y) :... p="local variable"... print locals()... return x+ y... >>> >>> add(1,2){'y': 2, 'p': 'local variable', 'x': 1}3

>>> add.__globals__

함수별로 자신의 이름공간을 관리 (dict())

함수 외부 환경에 대한 변수들을 관리하는 이름공간

Page 142: 파이썬정리 20160130

함수 결과 처리 -return/yield 함수는 처리결과를 무조건 처리한다 . Return 이 없는 경우에는 None 으로 결과를 처리 함수 결과는 하나의 결과만 전달

• 여러 개를 전달 할 경우 Tuple 로 묶어서 하나로 처리한다 .

return 를 yield 로 대체할 경우는 Generator 가 발생 • 함수가 메모리에 있다가 재호출 (next()) 하면 결과값을 처리

Page 143: 파이썬정리 20160130

Function Parameter

Page 144: 파이썬정리 20160130

함수 -Namespace : 인자관리 파이썬은 함수 인자와 함수 내의 로컬 변수를 동일하게 관리 .함수 인자와 함수 내의 로컬변수명이 같은 경우 동일한 것으로 처리

# 함수 정의def add(x, y) : return x+y

# 함수 실행 add(1,2) # 3 을 return

Add 함수 내의 로컬 영역에 인자를 관리하는 사전이 생기고 {‘x’: None, ‘y’:None}

Add 함수 내의 로컬 영역에 인자에 매핑 {‘x’: 1, ‘y’: 2}

Page 145: 파이썬정리 20160130

함수 인자 – mutable/immutable 함수가 실행시 함수 실행을 위한 프레임을 하나를 가지고 실행 반복적으로 함수를 호출 시 인자의 값이 참조 객체일 경우는 지속적으로 연결 인자에 참조형을 기본 인자로 사용하면 원하지 않는 결과가 생기므로 None으로 처리한 후 함수 내부에 참조형을 추가 정의해야 함

def f(a, l=[]) : l.append(a) return l

f(1)f(2)f(3)

함수정의

함수실행

{ ‘a’:1, ‘l’ :[1]}

함수 내부이름공간

{ ‘a’:2, ‘l’ :[1,2]}

{ ‘a’:2, ‘l’ :[1,2,3]}

f(1) 실행f(2) 실행f(3) 실행

실제 List 객체

참조객체를 함수 인자에 초기값으로 받을 경우 함수 호출시에 연결된게 남아있는다 .

def f(a, l=None) : l = [] l.append(a) return l

함수정의

인자에 변경가능한 값을 할당하지 않음

Page 146: 파이썬정리 20160130

외부변수를 함수 변수 활용함수의 인자를 함수 외부와 내부에서 활용하려면 mutable(변경가능 ) 한 객체로 전달하여 처리해야 Return 없이 값이 변경됨

함수를 정의 변수에는 참조만 가지고 있으므로 전체를 카피해야 리스트 원소들이 변경됨

Mutable 인 리스트로 값을 전달하여 swap() 처리 Return 이 없어도 실제 값이 변경됨

# 함수정의def swap(a,b) : x = a[:] a[:] = b[:] b[:] = x[:]

# 함수 실행a = [1]b = [2]print(swap(a,b))print(a,b) //[2] ,[1]

Page 147: 파이썬정리 20160130

함수 - 초기값 / 인자변수에 값할당 함수 내의 인자를 별도의 이름공간에 관리하므로 고정인자일 경우에도 이름에 값을 할당 가능

# 함수 정의def add(x=10, y) : return x+y

# 함수 실행 add(1,y=20) # 21 을 return

add 함수 내의 로컬 영역에 인자를 관리하는 사전이 생기고 {‘x’: 10, ‘y’:None}

add 함수 내의 로컬 영역에 인자에 매핑 {‘x’: 1, ‘y’: 20}

Page 148: 파이썬정리 20160130

함수 - 가변인자 - 값 (*args) 함수 인자의 개수가 미정일 경우 사용# 함수 정의def add(*arg) : x =0 for y in arg : x=x+y return x

# 함수 실행 add(1,2) # 3 을 return

add 함수 내의 로컬 영역에 인자를 관리하는 사전이 생기고 {‘arg’: None}

add 함수 내의 로컬 영역에 인자에 튜플 값으로 매핑 {‘arg’: (1,2) }

Page 149: 파이썬정리 20160130

함수 - 가변인자 - 키 / 값 (**args) 함수 인자의 개수가 미정이고 인자 변수를 정의할 경우 # 함수 정의def add(**arg) : return arg[‘x’] + arg[‘y’]

# 함수 실행 add(x=1,y=2) # 3 을 return

add 함수 내의 로컬 영역에 인자를 관리하는 사전이 생기고 {‘arg’: None}

add 함수 내의 로컬 영역에 인자에 사전으로 매핑 {‘arg’: { ‘x’:1,’y’:2} }

Page 150: 파이썬정리 20160130

Function Call

Page 151: 파이썬정리 20160130

함수 반복 호출함수도 호출 방법에 따라 다양한 구현 및 처리가 가능

연속 ( 재귀 ) 호출

특정 시점 호출

부분 호출

함수를 인자값을 바꿔가면 처리가 완료 될때까지 연속해서 호출하여 처리함수를 구동시켜 필요한 시점에 호출하여 결과 처리 (iteration, generation)

함수를 인자별로 분리하여 호출하면서 연결해서 결과를 처리

Page 152: 파이썬정리 20160130

함수 - 재귀호출함수 정의시 함수가 여러 번 호출될 것을 기준으로 로직을 작성해서 동일한 함수를 지속적으로 처리할 도록 호출

def factorial(n): print("factorial has been called with n = " + str(n)) if n == 1: return 1 else: result = n * factorial(n-1) print("intermediate result for ", n, " * factorial(" ,n-1, "): ",re-sult) return result

print(factorial(5))

자신의 함수를 계속 호출하면 stack 에 새로운 함수 영역이 생겨서 처리한다

Page 153: 파이썬정리 20160130

함수 – 시점 호출 iteration sequence 객체 등을 반복해서 사용할 수 있도록 지원하는 객체처리 방식

>>> l= [1,2,3,4]>>> iter(l)<listiterator object at 0x06585090>>>> li = iter(l)>>> li.next()1>>> li.next()2>>> li.next()3>>> li.next()4>>> li.next()Traceback (most recent call last): File "<stdin>", line 1, in <module>StopIteration>>>

Page 154: 파이썬정리 20160130

함수 – 시점 호출 :Generation 함수를 호출해도 계속 저장 함수를 호출 처리가 종료되면 exception 발생

>>> v = (i for i in l)>>> v<generator object <genexpr> at 0x06521E90>>>> v.next()0>>> v.next()1>>> v.next()2>>> v.next()3>>> v.next()4>>> v.next()Traceback (most recent call last): File "<stdin>", line 1, in <module>StopIteration>>>

>>> def returnfunc(x) :... for i in x :... yield i... >>> p = returnfunc([1,2,3])>>> p<generator object returnfunc at 0x06480918>>>> p.next()1>>> p.next()2>>> p.next()3>>> p.next()Traceback (most recent call last): File "<stdin>", line 1, in <module>StopIteration>>>

Generation Expression Generation Function

Page 155: 파이썬정리 20160130

함수 – 시점호출 : Generation – Function(yield) 함수 Return 대신 Yield 대체 함수를 호출 (next()) 해도 계속 저장 함수를 호출 처리가 종료되면 exception 발생

>>> def list_c(l) :... for i in l :... yield i... >>> list_c(l)<generator object list_c at 0x06521A08>>>> v = list_c(l)>>> v.next()0>>> v.next()1>>> v.next()2>>> v.next()3>>> v.next()4>>> v.next()Traceback (most recent call last): File "<stdin>", line 1, in <module>StopIteration>>>

Page 156: 파이썬정리 20160130

함수 - 부분호출 : Curry함수의 인자를 점진적으로 증가하면서 처리하는 법으로 외부함수에서 내부함수로 처리를 위임해서 점진적으로 실행하도록 처리하는 함수

def f(a): print "function class object ",id(f) def g(b, c, d, e): print(a, b, c, d, e) return g

print " function instance ", id(f(1))f1 = f(1)f1(2,3,4,5)

def f1(a): def g1(b): def h1(c, d, e): print(a, b, c, d, e) return h1 return g1

f1(1)(2)(3,4,5)

f1(1) 함수 실행하면 g1(2) 함수가 실행되고 h1 (3,4,5) 가 최종적으로 실행되여 결과는 (1,2,3,4,5) 출력

Page 157: 파이썬정리 20160130

함수 - 부분 호출 : partial파이썬에서는 partial 함수를 제공해서 함수를 분할하여 처리함

from functools import partialdef f2(a, b, c, d): print(a, b, c, d)

#<functools.partial object at 0x029CE210>

print partial(f2, 1, 2, 3)

g2 = partial(f2, 1, 2, 3)g2(4)

Partial 함수 객체를 생성하고 추가 인자를 받으면 처리(1,2,3,4) 출력

Page 158: 파이썬정리 20160130

Nested Function

Page 159: 파이썬정리 20160130

함수를 내부함수 정의함수는 사용하기 전에 정의해서 사용 .함수 내에 다시 함수를 정의하여 사용

# 외부 함수 정의def outer() : # 내부 함수정의 def inner() : pass

# 내부함수 실행 후 결과 전달 # 결과값은 아무것도 없음 return inner()

Page 160: 파이썬정리 20160130

함수를 내부함수 처리 함수 내부에 함수를 정의하고 함수 내부에서 실행하여 처리

def greet(name): # 내부 함수 정의 def get_message(): return "Hello “ # 내부함수 실행 result = get_message()+name return result

# 외부함수 실행print greet("Dahl")

함수 내부에 기능이 필요한 경우 내부 함수를 정의하여 호출하여 처리

Page 161: 파이썬정리 20160130

내외부 함수에 대한 변수 scope외부함수에 정의된 자유변수를 내부함수에서 활용하여 처리 가능단 , 내부함수에서 갱신할 경우 mutable 타입이 사용 해야 함

# 자유변수에 대한 스코핑def compose_greet_func(name): # 내부 함수 정의 # 외부 함수 자유변수 name 을 사용 def get_message(): return "Hello there "+name+"!“ # 내부함수를 함수 결과값으로 전달 return get_message# 함수실행greet = compose_greet_func(“Dahl")print greet()

Page 162: 파이썬정리 20160130

First Class Object

Page 163: 파이썬정리 20160130

First Class Object(1)일반적으로 First Class 의 조건을 다음과 같이 정의한다 . 변수 (variable) 에 담을 수 있다 인자 (parameter) 로 전달할 수 있다 반환값 (return value) 으로 전달할 수 있다 1급 객체 (first class object)

# 함수를 변수에 할당func = addprint func

# 함수를 함수의 인자로 전달def addplus(func,x,y) : return func(x,y) print addplus(add,5,5)

# 함수를 함수의 리턴 결과로 전달def addpass(func) : return func

print addpass(add)(5,5)

# 결과<function add at 0x041F7FB0>1010

Page 164: 파이썬정리 20160130

First Class Object(2) 1 급 함수 (first class object)

런타임 (runtime) 생성이 가능 익명 (anonymous) 으로 생성이 가능

# 함수를 함수의 리턴 결과로 전달def addpass(func) : return func

print addpass(add)(5,5)

#lambda 함수를 이용하여 익명으로 # 사용하지만 함수가 객체이므로 처리가됨print addpass(lambda x,y: x+y)(5,5)

Page 165: 파이썬정리 20160130

함수를 변수에 할당함수도 객체이므로 변수에 할당이 가능

함수 객체 함수인자객체함수명

( 참조주소 )

함수 정의변수

변수에 할당def swap(a,b) :x = a[:]a[:] = b[:]b[:] = x[:]

func_var = swap # 함수를 변수에 할당a = [1]b = [2]#print(swap(a,b))print(func_var(a,b))print(a,b)

변수는 참조를 저장하므로 함수의 참조도 변수에 저장되고 실행연산자( () ) 를 이용하여 처리 가능

Page 166: 파이썬정리 20160130

함수를 파라미터로 전달함수도 하나의 객체이며 데이터 타입이므로 파라미터인자로 전달이 가능외부에 함수를 정의하고 실행함수에 파라미터로 전달 후 실행함수 내부에서 실행

# 파라미터 전달 함수 정의def greet(name): return "Hello " + name # 실행 함수 정의def call_func(func): other_name = “Dahl“ # 파라미터 전달된 함수 실행 return func(other_name)

# 함수 실행print call_func(greet)

Page 167: 파이썬정리 20160130

함수 결과값을 함수로 전달함수 결과값을 함수정의된 참조를 전달해서 외부에서 전달받은 함수를 실행하여 처리

# 실행함수 정의def compose_greet_func(): # 내부함수 정의 def get_message(): return "Hello there!“ # 내부함수를 함수처리결과값으로 전달 return get_message

# 함수실행 : 결과값은 함수의 참조 전달# 함수를 변수에 할당greet = compose_greet_func()# 함수 실행 : 변수에 할당된 내부함수가 실행됨print greet()

Page 168: 파이썬정리 20160130

익명함수

Page 169: 파이썬정리 20160130

함수 - LambdaLambda 는 단순 처리를 위한 익명함수이고 return 을 표시하지 않는다 .익명함수를 정의하고 실행하지만 리턴 결과는 한 개만 전달 할 수 있다 .

Lambda 인자 : 표현식

함수 객체함수인자객체

함수명 미존재( 참조주소 )

익명함수 정의변수 필요시 변수에 할당

Page 170: 파이썬정리 20160130

함수 – Lambda 예시Lambda 는 표현식시 2 개의 리턴 값이 생기므로 에러가 발생함표현식에서 2 개 이상 결과를 나타내려면 tuple 처리해야 함

>>> x = lambda x,y : y,xTraceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'x' is not defined>>>>>> x = lambda x,y : (y,x)>>> x(1,2)(2, 1)

Page 171: 파이썬정리 20160130

Closure

Page 172: 파이썬정리 20160130

함수 – Closure : context외부함수 내의 자유변수를 내부함수에서 사용하면 기존 외부함수도 내부함수가 종료시까지 같이 지속된다 .함수 단위의 variable scope 위반이지만 현재 함수형 언어에서는 함수 내의 변수를 공유하여 처리할 수 있도록 구성하여 처리할 수 있도록 구성이 가능하다 .

외부함수

내부함수

외부함수이름공간

내부함수이름공간

Closure context 구성

내부함수 변수 검색 순서는 내부함수 이름공간 -> 외부함수 이름공간

Page 173: 파이썬정리 20160130

함수 – Closure : __closure__파이썬은 클로저 환경에 대해서도 별도의 객체로 제공하며 이 환경에 대해서도 접근이 가능함

def generate_power_func(n): out_v = 10.0 def nth_power(x): return x**n + out_v return nth_power

print clo.__closure__print clo.__closure__[0]print type(clo.__closure__[0])print clo.__closure__[0].cell_contentsprint type(clo.__closure__[1])print clo.__closure__[1].cell_contents

(<cell at 0x02940ED0: int object at 0x01DAABC4>, <cell at 0x02B6FEF0: float object at 0x02766600>)

<cell at 0x02940ED0: int object at 0x01DAABC4><type 'cell'>4<cell at 0x02B6FEF0: float object at 0x02766600>10.0

__closure__ 는 튜플로 구성되어 자유변수에 대해 객체로 구성됨

Page 174: 파이썬정리 20160130

함수 – Closure : 자유변수 (1)외부함수 내의 자유변수를 내부함수에서 사용하면 기존 외부함수도 내부함수가 종료시까지 같이 지속된다 .

def generate_power_func(n): print "id(n): %X" % id(n) print ' outer ', locals() def nth_power(x): print ' inner ', locals() #return x**n v = x**n # n = v + n #UnboundLocalError: local variable 'n' referenced #before assignment return v print "id(nth_power): %X" % id(nth_power) return nth_power

clo = generate_power_func(4)print clo(5)

자유변수가 im-mutable 일 경우 내부함수에 생기지만 변경할 수 없으므로 에러처리

Locals() 함수를 이용하여 함수에서 관리하는 변수를 출력outer {'n': 4}inner {'x': 5, 'n': 4}

Page 175: 파이썬정리 20160130

함수 – Closure : 자유변수 (2)변수는 Mutable 값과 Immutable 값이 binding 되면서 정의되므로 내부함수에서 외부함수의 변수 (immutable) 에 재할당 시 unboundlocalerror 발생시 해결 방안

내부함수에 키워드 nonlocal 를 변수에 사용 외부함수에 mutable 값을 할당한 변수를 사용 ( 리스트 , 사전으로 정의 )

외부함수Context

내부함수Context

Local Local

IntFloat string

Immutable 객체외부함수의 변수를 변경하려면 외부함수 context 에서 처리 되어야 함 함수의 인자 전달시 동일한 원칙이 발생

Page 176: 파이썬정리 20160130

Function Chaining

Page 177: 파이썬정리 20160130

함수 연속 실행함수 chian 은 함수를 결과값으로 받고 실행연산자(parameter) 를 연속하면 함수들을 계속 실행함

def chain(obj) : return obj def cc(obj): print obj chain(cc)('str')

함수 1 실행 하고 함수2 실행# 결과값str

Page 178: 파이썬정리 20160130

High Order Function

Page 179: 파이썬정리 20160130

High Order Function 고차함수 (high order function) 는 2 가지 중에 하나를 수행

하나 이상의 함수를 파라미터로 받거나 , 함수를 리턴 결과로 보내는 함수

# 고차 함수 정의def addList8(list): return reduce(add8, list)# 일반함수 정의def add8(*arg): v = [] for i in arg: v = v +i return v

# 고차함수 실행print addList8([[1, 2, 3],[4, 5],[6],[]])

print reduce(add8, [[1, 2, 3],[4, 5],[6],[]])

# 결과값[1, 2, 3, 4, 5, 6][1, 2, 3, 4, 5, 6]

Page 180: 파이썬정리 20160130

map 함수map(f, iterable) 은 함수 (f) 와 반복가능한 자료형(iterable) 을 입력으로 받아 입력 자료형의 각각의 요소가 함수 f 에 의해 수행된 결과를 묶어서 리턴하는 함수

# 파이썬 2 및 파이썬 3# 5 개 원소를 가진 리스트의 제곱하여 변환list(map(lambda x: x ** 2, range(5)))

# 결과값 : [0, 1, 4, 9, 16]

Page 181: 파이썬정리 20160130

reduce 함수reduce(f, iterable) 은 함수 (f) 와 반복가능한 자료형(iterable) 을 입력으로 받아 입력 자료형의 각각의 요소가 함수 f 에 의해 수행된 결과를 리턴하는 함수

def addList7(list): return reduce(add, list) def add(*arg): x = 0 for i in arg : x = x + i return x print "addlist", addList7([1, 2, 3])

print "reduce ", reduce(add, [1, 2, 3])

# 결과값addlist 6reduce 6

Page 182: 파이썬정리 20160130

filter 함수

# 파이썬 2 및 파이썬 3#10 개 원소중에 5 보다 작은 5 개만 추출 list(filter(lambda x: x < 5, range(10)))

# 결과값 : [0, 1, 2, 3, 4]

filter(f, iterable) 은 함수 (f) 와 반복가능한 자료형(iterable) 을 입력으로 받아 함수 f 에 의해 수행된 결과 즉 filter 된 결과를 리턴하는 함수

Page 183: 파이썬정리 20160130

Function Decorator

Page 184: 파이썬정리 20160130

Decorator 사용 기법 함수 Chain : 함수를 결과 값 처리 고차함수 클로저 functools 모듈의 wraps 함수 사용

Page 185: 파이썬정리 20160130

Decorator : functools 사용이유 functools 모듈의 wraps 함수 사용을 할 경우 __doc__/__name__ 이 삭제되지 않고 함수의 것을 유지

Page 186: 파이썬정리 20160130

Decorator 처리 흐름 Decorator 함수 내부에 내부함수를 정의해서 파라미터로 받은 함수를 wrapping 하여 리턴 처리하고 최종으로 전달함수를 실행 함수 Chain 처리 ( 버블링 )

함수 1 함수 2함수 3( 전달함수 )

함수 2( 함수3)

함수 3실행함수 1( 함수 2( 함수3))

@f1 @f2

Decorator 순서

함수 1( 함수 2( 함수 3))(전달변수 ) 함수호출 순서

Page 187: 파이썬정리 20160130

Decorator 단순 예시 Decorator 는 함수의 실행을 전달함수만 정의해도 외부함수까지 같이 실행된 결과를 보여준다 .

def func_return(func) : return func

def x_print() : print(" x print ")

x = func_return(x_print)x()

def func_return(func) : return func

@func_returndef r_print() : print (" r print ")

r_print()

외부함수

전달함수함수 실행

Page 188: 파이썬정리 20160130

Decorator : 단순 wrapping 예시 Decorator 되는 함수에 파라미터에 실행될 함수를 전달되고

내부함수인 wrapping 함수를 리턴 Wrapping 함수 내부에 전달함수를 실행하도록 정의 데코레이터와 전달함수 정의 전달함수를 실행하면 데코레이터 함수와 연계해서 실행 후 결과값 출력

def common_func(func) : def wrap_func() : return func() return wrap_func

@common_funcdef r_func() : print " r func "

데코레이터 함수 정의 전달 함수 및 데코레이션 정의 함수 할당 및 실행

r_func()

# 처리결과 r func

Page 189: 파이썬정리 20160130

Decorator: 전달함수 ( 파라미터 ) Decorator 할 함수를 정의하여 기존 함수 처리말고 추가 처리할 부분을 정의 실제 실행할 함수 즉 전달함수를 정의 실행할 함수를 실행하면 decorator 함수까지 연계되어 처리됨

def outer_f(func) :

def inner_f(*arg, **kargs) : result = func(*arg, **kargs) print(' result ', result) return result return inner_f

@outer_fdef add_1(x,y): return x+y

데코레이터 함수 정의 전달 함수 및 데코레이션 정의 함수 할당 및 실행

# 데코레이터 호출 x = add_1(5,5)print(' decorator ', x)

# 함수 처리 순서v = outer_f(add)v(5,5)

Page 190: 파이썬정리 20160130

Functools Modulefunctools.wraps(wrapped[, assigned][, up-dated]) 을 이용하여 데코레이션 처리

from functools import wrapsdef my_decorator(f): @wraps(f) def wrapper(*args, **kwds): print 'Calling decorated function' return f(*args, **kwds) return wrapper

@my_decoratordef example(): """Docstring""" print 'Called example function'

example()

1. Functool 를 import 처리2. @wraps( 전달함수 )3. Wrapper 로 함수에 파라미터 전달 4. 데코레이션 정의5. 전달함수 작성6. 전달함수 실행

Page 191: 파이썬정리 20160130

Function decorator : 파라미터 데코레이터 함수에서 사용할 파라미터 전달 내부함수에 전달함수를 파라미터로 전달 ( 클로저 구성 ) wrapping 함수 정의 및 내부함수 파라미터 전달

def tags(tag_name): def tags_decorator(func): def func_wrapper(name): return "<{0}>{1}</{0}>".format(tag_name, func(name)) return func_wrapper return tags_decorator

@tags("p")def get_text(name): return "Hello "+name

# 함수 실행print get_text("Dahl")

Page 192: 파이썬정리 20160130

Functools Modulefunctools.wraps(wrapped[, assigned][, up-dated]) 을 이용하여 데코레이션 처리

from functools import wrapsdef my_decorator(f): @wraps(f) def wrapper(*args, **kwds): print 'Calling decorated function' return f(*args, **kwds) return wrapper

@my_decoratordef example(): """Docstring""" print 'Called example function'

example()

1. Functool 를 import 처리2. @wraps( 전달함수 )3. Wrapper 로 함수에 파라미터 전달 4. 데코레이션 정의5. 전달함수 작성6. 전달함수 실행

Page 193: 파이썬정리 20160130

복수 Function decorator 순서실행 func 을 호출시 실행 순서는decorate1(decorate2(decorat3(func))) 로 자동으로 연결하여 처리됨

#decorate1 def decorate1 : pass#decorate2 def decorate2 : pass#decorate3 def decorate3 : pass

@decorate1@decorate2@decorate3def func : pass

Page 194: 파이썬정리 20160130

Functools Module: 파라미터데코레이터 파라미터를 처리하기 위해 파라미터 처리하는 함수를 하나 더 처리

from functools import wrapsdef my_decorator0(x) : print x def my_decorator1(f): @wraps(f) def wrapper(*args, **kwds): print 'Calling decorated function' return f(*args, **kwds) return wrapper return my_decorator1

@my_decorator0('xxx')def example1(): """Docstring""" print 'Called example function' example1()

1. 데코레이터 파라미터 처리함수 정의 2. Functool 를 import 처리3. @wraps( 전달함수 )4. Wrapper 로 함수에 파라미터 전달 5. 데코레이션 정의6. 전달함수 작성7. 전달함수 실행

Page 195: 파이썬정리 20160130

복수 Function decorator 예시함수 호출 순서는 f1(f2(add))(5,5) 로 자동으로 연결하여 처리됨

#decorator 함수 1def f1(func) : def wrap_1(*args) : return func(*args) print " f1 call" return wrap_1

#decorator 함수 2 def f2(func) : def wrap_2(*args) : return func(*args) print "f2 call" return wrap_2

#decorator 처리 @f1@f2def add(x,y) : print " add call " return x +y print add(5,5)

# 함수연결 호출print f1(f2(add))(5,5)

#decorator 처리 결과f2 call f1 call add call 10# 함수 연결 처리결과f2 call f1 call add call 10

Decorator 함수 정의 함수 실행

Page 196: 파이썬정리 20160130

CLASS

Page 197: 파이썬정리 20160130

Class 기초

Page 198: 파이썬정리 20160130

Class 란파이썬 언어에서 객체를 만드는 타입을 Class 로 생성해서 처리Class 는 객체를 만드는 하나의 틀로 이용자바 언어와의 차이점은 Class 도 Object 로 인식

Class

Object 1

Object 1

Object 1

instance

class 클래스이름 [( 상속 클래스명 )]: < 클래스 변수 1> < 클래스 변수 2> ... def 클래스함수 1(self[, 인수 1, 인수 2,,,]): < 수행할 문장 1> < 수행할 문장 2> ... def 클래스함수 2(self[, 인수 1, 인수 2,,,]): < 수행할 문장 1> < 수행할 문장 2> ... ...

클래스에서 객체 생성하기

Page 199: 파이썬정리 20160130

Class 작성 예시

class Employee: 'Common base class for all employees' empCount = 0

def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print "Total Employee %d" % Employee.empCount

def displayEmployee(self): print "Name : ", self.name, ", Salary: ", self.salary

Class 객체 변수

Instance 객체 변수

Class 내의 인스턴스 메소드

파이썬에서 클래스는 하나의 타입이면서 하나의 객체이다 . 실제 인스턴스 객체를 만들 수 있는 타입으로 사용

Page 200: 파이썬정리 20160130

Int Class 설명 예시

>>> dir(int)['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__-doc__', '__float__', '__floordiv__', '__format__', '__ge-tattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__re-duce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'de-nominator', 'imag', 'numerator', 'real']>>>

Int Class 에는 __del__() 즉 소멸자가 없다 . 동일한 값을 생성하면 동일한 인스턴스를 가진게 된다 .같은 context 환경하에서는 생성된 객체 인스턴스는 동일하게 사용한다 .

int Class 내부 멤버

>>> v = int(1)>>> w = int(1)>>> z = int(1)>>> id(v)5939944>>> id(w)5939944>>> id(z)5939944>>> v = 2>>> id(v)5939932>>> id(1)5939944>>> v=1>>> id(v)5939944

int Object instance 생성

Page 201: 파이썬정리 20160130

Class Object & instanceClass Object 는 인스턴스를 만드는 기준을 정리한다 . 클래스를 정의한다고 하나의 저장공간 (Namespace) 기준이 되는 것은 아니다 . - 클래스 저장공간과 인스턴스 저장공간이 분리된다

User de-finedClass

Instance

Instance

Instance

Built-inClass

상속 인스턴스화

Object Scope

Object Namespace

Page 202: 파이썬정리 20160130

Class Member

Page 203: 파이썬정리 20160130

Class MemberClass Object 는 클래스 메소드 , 정적메소드 , 클래스 내부 변수 등을 관리한다 .

class Class_Member : cls_var = 0 @classmethod def cls_method(cls) : cls.cls_var = 1 print("call cls_method ", cls.cls_var)

@staticmethod def sta_method() : cls_var = 100 print("call sta_method ", cls_var)

def ins_method(self) : self.ins_var = 1 print('call ins method ', self.ins_var)

c = Class_Member()c.ins_method()print(c.__dict__)

클래스 변수클래스 객체 메소드클래스 정적 메소드

# 처리결과('call cls_method ', 1)('call sta_method ', 100)#Class_Member 내부 관리 영역{'sta_method': <staticmethod object at 0x0215A650>, '__module__': '__main__', 'ins_method': <function ins_method at 0x029D2270>, 'cls_method': <classmethod object at 0x01D92070>, 'cls_var': 1, '__doc__': None}

인스턴스 메소드

Page 204: 파이썬정리 20160130

Predefined Class At-tributes

Attribute Type Read/Write Description

__dict__ dictionary R/W The class name space.

__name__ string R/O The name of the class.

__bases__ tuple of classes R/O The classes from which this class inherits.

__doc__ string OR None R/W The class documentation string

__module__ string R/W The name of the module in which this class was defined.

Page 205: 파이썬정리 20160130

Instance MemberInstance 생성시 self 로 정의된 변수만 인스턴스 영역에서 관리하고 인스턴스 메소드는 클래스에서 관리함

class Class_Member : cls_var = 0 @classmethod def cls_method(cls) : cls.cls_var = 1 print("call cls_method ", cls.cls_var) @staticmethod def sta_method() : cls_var = 100 print("call sta_method ", cls_var)

def ins_method(self) : self.ins_var = 1 print('call ins method ', self.ins_var)

c = Class_Member()c.ins_method()print(c.__dict__)

인스턴스 변수

# 처리결과('call ins method ', 1){'ins_var': 1} # 인스턴스 객체 관리 영역

Page 206: 파이썬정리 20160130

Predefined Instance Attributes

Attribute Type Read/Write Description

__dict__ dictionary R/W The instance name space.

__class__ Base class R The base class

__doc__ string OR None R/W The instance documentation string

Page 207: 파이썬정리 20160130

메소드 접근자

Page 208: 파이썬정리 20160130

Class 멤버 접근자 - cls클래스 객체의 변수나 메소드 접근을 위해 cls 키워드 사용

Page 209: 파이썬정리 20160130

Instance 멤버 접근자 -self인스턴스객체 메소드의 첫 인자는 Self 를 사용하여 각 인스턴스별로 메소드를 호출하여 사용할 수 있도록 정의

Page 210: 파이썬정리 20160130

Method- 인스턴스 객체클래스 객체에서 생성되는 모든 인스턴스 객체에서 활용되므로 클래스 이름공간에서 관리메소드 첫 파라미터에 self 라는 명칭을 정의

Page 211: 파이썬정리 20160130

Method- 클래스 decorator클래스 객체에서 처리되는 메소드를 정의한다 . 클래스 메소드는 첫번째 파라미터에 cls 를 전달한다 .

장식자 @classmethod : 클래스 함수 위에 표시 -Python 2.x함수 classmethod() : 별도 문장으로 표시 – Python 3.x

인스턴스 객체도 호출이 가능

Page 212: 파이썬정리 20160130

Method- 정적 decorator클래스 객체로 생성된 모든 인스턴스 객체가 공유하여 사용할 수 있다 .

장식자 @staticmethod : 정적함수 위에 표시 – Python 2.x함수 staticmethod() 는 별도의 문장으로 표시 – Python 3.x

정적메소드는 파라미터에 별도의 self, cls, 등 객체에 대한 참조값을 전달하지 않아도 됨 인스턴스 객체에서도 호출이 가능

Page 213: 파이썬정리 20160130

Accessing Members클래스를 정의한 후에 인스턴스를 생성하고 메소드 호출 및 클래스 변수를 직접 호출하여 출력

class Employee: 'Common base class for all employees‘ empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print "Total Employee %d" % Employee.emp-Count def displayEmployee(self): print "Name : ", self.name, ", Salary: ", self.salary

Class 정의# 인스턴스 객체 생성 : 생성자 호출emp1 = Employee("Zara", 2000) # 인스턴스 메소드 호출emp1.displayEmployee()

# 인스턴스 객체 생성 : 생성자 호출emp2 = Employee("Manni", 5000) # 인스턴스 메소드 호출emp2.displayEmployee()

# 클래스 변수 호출 및 출력print "Total Employee %d" % Employee.empCount

Instance 생성 및 호출

Page 214: 파이썬정리 20160130

Method Bound/unbound(1)클래스이름과 인스턴스이름으로 메소드를 호출하면 binding 처리 됨메소드 선언시 인자로 self, cls 를 정의되어 있음

>>> class Preson() :... def printP(self) :... print(' instance method ')... def printC(cls) :... print(' class method')… >>> p = Preson() # 인스턴스 생성>>> p.printP() # 인스턴스 메소드 binding instance method >>> Preson.printP(p) # 인스턴스 메소드 unbinding instance method >>>

인스턴스를 생성하고 인스턴스 메소드 호출시는 binding 처리 클래스로 인스턴스 메소드 호출시는 인자로 인스턴스 객체를 전달해서 unbinding

Page 215: 파이썬정리 20160130

Method Bound/unbound(2)메소드 선언시 인자로 self, cls 를 정의되어 있는 것에 따라 매칭시켜야 됨

Transformation Called from an Object Called from a Class

Instance method f(*args) f(obj,*args)

Static method f(*args) f(*args)

Class method f(cls, *args) f(*args)

Page 216: 파이썬정리 20160130

Method & Object Chain

Page 217: 파이썬정리 20160130

Method Chain

class Person: def name(self, value): self.name = value return self def age(self, value): self.age = value return self def introduce(self): print "Hello, my name is", self.name, "and I am", self.age, "years old."

person = Person() # 객체의 메소드를 연속적으로 호출하여 처리person.name("Peter").age(21).introduce()

객체들간의 연결고리가 있을 경우 메소드 결과값을 객체로 받아 연속적으로 실행하도록 처리

Page 218: 파이썬정리 20160130

Object Chain

#class 정의하고 인스턴스에서 타 객체를 호출class A: def __init__(self ): print 'a' self.b = B()

#object chain 을 하는 class 생성class B: def __init__(self ): print 'b' def bbb(self): print "B instance method " a = A()

print a.b.bbb()

객체들간의 연결고리 (Association, Composite 관계 ) 가 있을 경우 메소드 결과값을 객체로 받아 연속적으로 실행하도록 처리

객체 . 내부객체 .메소드 처리# 결과값abB instance method None

Page 219: 파이썬정리 20160130

생성자와 소멸자

Page 220: 파이썬정리 20160130

생성자 -Creating Instance 파이썬 생성자 __init__() 함수를 오버라이딩한 후클래스이름 ( 파라미터 ) 를 이용하여 객체 생성생성자 함수는 자동으로 연계됨

class Employee: 'Common base class for all employees' empCount = 0

def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1

"This would create first object of Employee class"emp1 = Employee("Zara", 2000)"This would create second object of Employee class"emp2 = Employee("Manni", 5000)

생성자 정의

인스턴스 객체 생성생성자와 자동으로 연계

Page 221: 파이썬정리 20160130

소멸자 - Destroying Objects클래스의 생성된 인스턴스를 삭제하는 메소드

#!/usr/bin/python

class Point: def __init( self, x=0, y=0): self.x = x self.y = y def __del__(self): class_name = self.__class__.__name__ print class_name, "destroyed"

pt1 = Point()pt2 = pt1pt3 = pt1print id(pt1), id(pt2), id(pt3) # prints the ids of the obejctsdel pt1del pt2del pt3

소멸자 정의

소멸자 활용

Page 222: 파이썬정리 20160130

Class 구조

Page 223: 파이썬정리 20160130

클래스 구조 알기 (1)>>> one = 1>>> type(one)<type 'int'>>>> type(type(one))<type 'type'>>>> type(one).__bases__(<type 'object'>,)>>> >>> object <type 'object'>>>> type <type 'type'> >>> type(object) <type 'type'>>>> object.__class__ <type 'type'>>>> object.__bases__ ()>>> type.__class__ <type 'type'>>>> type.__bases__ (<type 'object'>,)>>> isinstance(object, object) True>>> isinstance(type, object) True>>> isinstance(object, type)True

objecttype

int float str

클래스 구조

Page 224: 파이썬정리 20160130

클래스 구조 알기 (2)

>>> list <type 'list'>>>> list.__class__ <type 'type'>>>> list.__bases__ (<type 'object'>,)>>> tuple.__class__, tuple.__bases__ (<type 'type'>, (<type 'object'>,))>>> dict.__class__, dict.__bases__ (<type 'type'>, (<type 'object'>,))>>>>>> mylist = [1,2,3] >>> mylist.__class__ <type 'list'>

데이터 타입은 상속을 받을 때 타입 객체를 바로 받지만 base 는 object 클래스를 처리 객체 생성 예시

메타클래스 클래스 인스턴스

type object

list mylist

Page 225: 파이썬정리 20160130

issubclass/isinstance 함수

>>> issubclass(list,object)True>>> list.__bases__(<type 'object'>,)>>> issubclass(list, type)False>>>

issubclass() : __bases__ 기준으로 상속관계 isinstance() : __ class__ 기준으로 인스턴스 객체 관계

>>> isinstance(list, type)True>>> list.__class__<type 'type'>>>> >>> isinstance(list, object)True>>>

issubclass 처리 isinstance 처리

Page 226: 파이썬정리 20160130

Class & instance namespaceClass Object 는 클래스 메소드 , 정적메소드 , 클래스 내부 변수 등을 관리한다 .파이썬은 변수나 메소드 검색 기준이 인스턴스 > 클래스 > Built-in Class 순으로 매칭시키므로 . 연산자를 이용하여 인스턴스도 메소드 호출이 가능하다 .

>>> class Simple : ... pass... >>> Simple<class __main__.Simple at 0x0212B228>>>> Simple.__name__'Simple‘>>> Simple.__dict__{'__module__': '__main__', '__doc__': None}

>>> s = Simple()>>> s.__dict__{}>>> s.name = "Simple instance">>> s.__dict__{'name': 'Simple instance'}

Instance 생성 및 인스턴스 멤버 추가Class 정의

Page 227: 파이썬정리 20160130

클래스와 인스턴스 접근

Page 228: 파이썬정리 20160130

Members( 변수 ) AccessClass/Instance 객체에 생성된 변수에 대한 구조 및 접근 방법

>>> # class 정의 >>> class C(object): ... classattr = "attr on class“... >>> # 객체 생성 후 멤버 접근>>> cobj = C() >>> cobj.instattr = "attr on instance" >>> >>> cobj.instattr 'attr on instance' >>> cobj.classattr 'attr on class‘

멤버접근연사자 (.) 를 이용하여 접근

C

classattr

cobj:C

instattr

cobj = C()

Page 229: 파이썬정리 20160130

Members( 변수 ) Access - 세부Class/Instance 객체는 내장 __dict__ 멤버 ( 변수 )에 내부 정의 멤버들을 관리함

>>> # 내장 __dict__ 를 이용한 멤버 접근 >>> # Class 멤버>>> C.__dict__['classattr'] 'attr on class' >>> # Instance 멤버>>> cobj.__dict__['instattr'] 'attr on instance' >>>>>> C.__dict__ {'classattr': 'attr on class', '__module__': '__main__', '__doc__': None}>>>>>>>>> cobj.__dict__ {'instattr': 'attr on instance'} >>>

C

cobj:C

cobj = C()

__dict__:dict

classattr

__dict__:dict

classattr

내장 객체

내장 객체

Page 230: 파이썬정리 20160130

Members( 메소드 ) AccessClass 정의시 인스턴스 메소드 정의를 하면 Class 영역에 설정

>>> #Class 생성>>> class C(object): ... classattr = "attr on class“... def f(self):... return "function f" ... >>> # 객체 생성>>> cobj = C() >>> # 변수 비교>>> cobj.classattr is C.__dict__['classattr'] True

변수 비교

C

classattr

f

cobj:C

instattr

cobj = C()

Page 231: 파이썬정리 20160130

Members( 메소드 ) Access- 세부인스턴스에서 인스턴스메소드 호출하면 실제 인스턴스 메소드 실행환경은 인스턴스에 생성되어 처리

>>> # 인스턴스에서 실행될 때 바운드 영역이 다름>>> # is 연산자는 동일 객체 체계>>> cobj.f is C.__dict__['f'] False >>>>>> C.__dict__ {'classattr': 'attr on class', '__mod-ule__': '__main__', '__doc__': None, 'f': <function f at 0x008F6B70>} >>> 인스턴스에 수행되는 메소드 주소가 다름>>> cobj.f <bound method C.f of <__main__.C instance at 0x008F9850>> >>> # 인스턴스 메소드는 별도의 영역에 만들어짐>>> # 인스턴스 내에 생성된 메소드를 검색>>> C.__dict__['f'].__get__(cobj, C) <bound method C.f of <__main__.C instance at 0x008F9850>>

C

cobj:C

cobj = C()

__dict__:dict

classattr

f

__dict__:dict

classattr

f

내장 객체

내장 객체

Page 232: 파이썬정리 20160130

Controlling Attribute AccessInstance 의 Attribute 에 대한 접근을 할 수 있는 내부 함수__getattr__(self, name)__setattr__(self, name, value)__delattr__(self, name)__getattribute__(self, name)

Page 233: 파이썬정리 20160130

Controlling Attribute Access인스턴스의 속성에 대한 접근을 내부 함수로 구현하여 접근

class A() : __slots__ =['person_id', 'name'] def __init__(self, person_id, name) : self.person_id = person_id self.name = name def __getattr__(self, name) : return self.__dict__[name] def __setattr__(self, name, value): if name in A.__slots__ : self.__dict__[name] = value else: raise Exception(" no match attribute") def __delattr__(self, name) : del self.__dict__[name]

def __getattribute__(self, name): return self.__dict__[name]

a = A(1,'dahl')

print a.__getattr__('name')print a.__getattr__('person_id')

print a.__dict__

print a.__setattr__('name','moon')print a.__setattr__('person_id',2)

print a.__getattr__('name')print a.__getattr__('person_id')

print a.__delattr__('name')print a.__dict__

a.name = 'gahl'

#a.s = 1

print a.__dict__

Page 234: 파이썬정리 20160130

Class Inheritance

Page 235: 파이썬정리 20160130

Inheritance상속은 상위 클래스를 하나 또는 여러 개를 사용하는 방법 class 상위 클래스명 : pass class 클래스명 ( 상위 클래스명 ) : pass

상속 정의시 파라미터로 상위 클래스명을 여러 개 작성시 멀티 상속이 가능함 class 클래스명 ( 상위 클래스명 , 상위 클래스명 ) : pass

Page 236: 파이썬정리 20160130

Inheritance- scope

상속된 클래스도 검색하는 순서가 파라미터를 정리한 순서대로 변수나 메소드를 검색하여 처리됨상속된 클래스에 동일한 이름이 변수나 메소드가 존재시 첫번째 검색된 것으로 처리함class 클래스명 ( 상위 클래스명 , 상위 클래스명 ) : pass

Page 237: 파이썬정리 20160130

Inheritance - 예시

class Parent: # define parent class parentAttr = 100 def __init__(self): print "Calling parent constructor“ def parentMethod(self): print 'Calling parent method' def setAttr(self, attr): Parent.parentAttr = attr def getAttr(self): print "Parent attribute :", Parent.parentAttr

class Child(Parent): # define child class def __init__(self): print "Calling child constructor" def childMethod(self): print 'Calling child method'

c = Child() # instance of childc.childMethod() # child calls its method c.-parentMethod() # calls parent's method c.se-tAttr(200) # again call parent's method c.getAttr() # again call parent's method

# 결과값Calling child constructor Calling child method Calling parent method Parent attribute : 200

Class 정의 인스턴스 생성 및 호출

Page 238: 파이썬정리 20160130

Mixin기존 상속구조에 대한 변경을 최소화하기 위해 메소드기반의 클래스 생성하여 상속받아 처리하는 방법

class Mixin : def add(self,x,y) : return self.x + self.y def sub(self,x,y) : if isinstance(self, String) : return " String no support" else : return self.x - self.y

class Number(Mixin) : def __init__(self, x,y) : self.x = x self.y = y

class String(Mixin) : def __init__(self, x,y) : self.x = x self.y = y

n1 = Number(5,6)n1.add(n1.x,n1.y)n1.sub(n1.x,n1.y)

s1 = String("hello ", "world")print s1.add(s1.x, s1.y)print s1.sub(s1.x, s1.y)

인스턴스 생성 및 호출

Page 239: 파이썬정리 20160130

Overriding

Page 240: 파이썬정리 20160130

Overriding메소드를 이름으로 검색하므로 하위 클래스에 동일한 메소드가 존재하면 인스턴스 호출시 하위 클래스 메소드 부터 호출하므로 Overriding 처리 class 상위 클래스명 : def method(self) : pass class 클래스명 ( 상위 클래스명 ) : def method(self) : pass

Page 241: 파이썬정리 20160130

연산자 OverridingBuiltin 연산자에 대한 메소드 등에 대해서는 클래스 내에 재정의해서 처리 가능

class Vector: def __init__(self, a, b): self.a = a self.b = b def __str__(self): return 'Vector (%d, %d)' % (self.a, self.b) def __add__(self,other): return Vector(self.a + other.a, self.b + other.b)

# __init__ 생성자 메소드 overridingv1 = Vector(2,10) v2 = Vector(5,-2)

# __add__ 메소드 overriding print v1 + v2

Page 242: 파이썬정리 20160130

Information Hiding

Page 243: 파이썬정리 20160130

Information hiding - 변수__ 명칭 : Private ( 객체 내부에서만 사용 ) 외부에서 호출시 mangling 되는 구조로 요청시 접근 가능 인스턴스 ._ 클래스명 __ 명칭_ 명칭 : protected ( 클래스 및 하위 클래스에서만 사용 )

Page 244: 파이썬정리 20160130

Information hiding - 변수예시 명칭 : public (파이썬은 공개되는 게 기본 ) __명칭 : Private (객체 내부에서만 사용 ) mangling 되는 구조로 명칭이 변경됨 호출시는 인스턴스 ._클래스명__명칭 _명칭 : protected (클래스 및 하위 클래스에서만 사용권고 ) “don’t touch this, unless you’re a subclass”

>>>class foo: … def __secret(self): pass …

foo.__secret => AttributeError: __secret

>>>foo.__dict__{'_foo__secret': <function __secret at fc328>, '__module__': '__main__', '__doc__': None}

Private 메소드 정의 및 호출 Class Namespace 명칭

Page 245: 파이썬정리 20160130

Information hiding – 변수 - 특별 __ 명칭 __ : 내장된 변수나 함수 등을 정의

Page 246: 파이썬정리 20160130

Information hiding –Descriptor(Property)

파이썬은 Property 객체를 이용하여 객체내의 변수들의 접근을 메소드로 제어한다 .Descriptor 객체 , Property 객체나 @property decorator 를 이용인스턴스 객체의 변수 명과 동일한 property 객체가 생성되어야 함

Class P Instance p1{‘x’: }

Descriptor/Property

x

생성

인스턴스생성

p1.x 접근

Property 내 메소드 호출하여 처리

Page 247: 파이썬정리 20160130

DESCIPTOR

Page 248: 파이썬정리 20160130

Descriptor Protocol

Page 249: 파이썬정리 20160130

Descriptor설명은 그 속성 접근 기술자 프로토콜의 방법에 의해 무시되었다 " 바인딩 행동 " 을 가진 객체 속성 중 하나입니다 __get__(self, instance, owner),__set__(self,instance, value),__delete__(self, instance).

Page 250: 파이썬정리 20160130

Descriptor 종류Method descriptor 와 Data descripter 로 구분

Method descriptor 는 __get__(self, instance, owner) 구현

Data descriptor 는 __get__(self, instance, owner) __set__(self,instance, value),

__delete__(self, instance) 구현

Page 251: 파이썬정리 20160130

Descriptor : int.__add__Method descriptor 로 구현되어 __get__(self, instance, owner) 가지고 있다

P =1# 직접 호출p.__add__(3) # 결과값 4# 인스턴스에서 호출type(p).__add__.__get__(p,int)(3) # 결과값 4#class 에서 호출int.__add__.__get__(1,int)(3)

Page 252: 파이썬정리 20160130

Descriptor : binding behavior

binding 하는 법Direct Call

Instance Bind-ing

Class Binding

Super Binding

class D(object) : def __init__(self, x) : self.x = x def __get__(self,instance=None,cls=None) : return self.x class D1(D) : def __init__(self, x) : D.__init__(self,x)

d = D(1)print " d"print d.__dict__print d.xprint " direct call",d.__get__()print " Class binding call ",D.__get__(d,d)print "instance binding",type(d).__get__(d,d)d1 = D1(2)print " d1"print d1.__dict__print d1.xprint " direct call",d1.__get__()print " Class binding call ", D1.__get__(d1,d1)print "instance binding",type(d1).__get__(d1,d1)print D1.mro()print "super binding",super(D1,d1).__get__(d1,d1)

Page 253: 파이썬정리 20160130

Creating descriptorDescriptor 클래스를 생성해서 처리하는 방법

class Descriptor(object): def __init__(self): self._name = '' def __get__(self, instance, owner): print "Getting: %s" % self._name return self._name def __set__(self, instance, name): print "Setting: %s" % name self._name = name.title() def __delete__(self, instance): print "Deleting: %s" %self._name del self._name

class Person(object): name = Descriptor()

>>> user = Person() >>> user.name = 'john smith' Setting: john smith >>> user.name Getting: John Smith 'John Smith‘>>> del user.name Deleting: John Smith

Page 254: 파이썬정리 20160130

Creating Property- 객체 직접 정의 (1)

인스턴스 객체의 변수 접근을 메소드로 제약하기 위해서는 Property 객체로 인스턴스 객체의 변수를 Wrapping 해야 함property(fget=None, fset=None, fdel=None, doc=None)

class P:

def __init__(self,x): self.x = x def getx(self) : return self.x def setx(self, x) : self.x = x def delx(self) : del self.x

x = property(getx,setx,delx," property test ")

Getter, setter, deleter 메소드를 정의

인스턴스 객체의 변수명과 동일하게 Property 객체 생성 ( 내부에 _x 생김 )

Page 255: 파이썬정리 20160130

Creating Property– 객체 직접 정의 (2)

실제 인스턴스 객체의 변수에 접근하면 Property 객체의 메소드를 호출하여 처리되고 인스턴스 객체의 변수값이 변경됨

p1 = P(1001)print id(p1.x)print P.__dict__['x']print id(p1.__dict__['x'])print p1.xp1.x = -12print p1.xprint p1.__dict__

# 처리결과값44625868<property object at 0x02C1D4E0>446258681001-12{'x': -12}

Page 256: 파이썬정리 20160130

Creating Property decorator(1)

인스턴스 객체의 변수 접근을 메소드로 제약하기 위해서는 Property 객체로 인스턴스 객체의 변수를 Wrapping 해야 함property(fget=None, fset=None, fdel=None, doc=None)

class P:

def __init__(self,x): self.x = x @property def x(self): return self.__x @x.setter def x(self, x): self.__x = x @x.deleter def x(self): del self.x

Getter, setter, deleter 메소드를 정의인스턴스 객체의 변수명과 동일하게 Property 객체 생성 ( 내부에 _x 생김 )

Page 257: 파이썬정리 20160130

Creating Property decorator(2)

Property 객체 생성하여 처리하는 방식과 동일

p1 = P(1001)print id(p1.x)print P.__dict__['x']print id(p1.__dict__['x'])print p1.xp1.x = -12print p1.xprint p1.__dict__

# 처리결과값44625916<property object at 0x02C1D3C0>446259161001-12{'x': -12}

Page 258: 파이썬정리 20160130

OBJECT

Page 259: 파이썬정리 20160130

Object

Page 260: 파이썬정리 20160130

왜 모든 것을 객체로 관리하나 ?

모든 것은 객체

값 문자열컨테이너

함수클래스

튜플리스트

딕션너리

집합

파이썬은 모든 것을 객체로 인식한다 . 데이터 구조가 다 객체이므로 클래스를 가지고 생성시 참조를 가지고 있음

파일모듈 패키지

모듈

Page 261: 파이썬정리 20160130

타입에 대한 예약어는 클래스 ?파이썬은 모든 것을 객체로 관리하므로 키워드도 내장된 클래스 객체

>>> type<type 'type'>>>> int<type 'int'>>>> float<type 'float'>>>> str<type 'str'>>>> list<type 'list'>>>> tuple<type 'tuple'>>>> dict<type 'dict'>>>> file<type 'file'>>>> re<module 're' from 'C:\Python27\lib\re.pyc'>>>> re.__class__<type 'module'>

Page 262: 파이썬정리 20160130

Object Scope 객체들간의 관계 ( 상속 및 instance 생성 등 ) 에 따라 객체 멤버들에 대한 접근을 처리검색 순서 : 인스턴스 > 클래스 > 상속클래스 >builtin Class

상속이 많아지면 다양한 상위 멤버들을 접근하여 처리할 수 있다 .

Page 263: 파이썬정리 20160130

Predefined Instance Attributes

Attribute Type Read/Write Description__dict__ dictionary R/W The instance name space__class__ class R/W The class of this instance

Page 264: 파이썬정리 20160130

Literal 처리

Page 265: 파이썬정리 20160130

왜 객체화 했을까 ?

값 객체

수치값문자열튜플

Immutuable( 값객체 )

Mutuable( 참조객체 )

리스트딕션너리

파이썬은 모두 객체이므로 변경여부 관리가 중요하다 .객체가 생성되고 함수 파라미터 등으로 전달될 때에도 변경이 가능한 객체와 불가능한 객체를 동일한 방식으로 관리한다 .

Page 266: 파이썬정리 20160130

Value 갱신 기준 Immutuable( 값객체 ) : 변수에 저장된 것을 값으로 인식하여 변수를 치환이 가능하지만 변경은 안됨 - 문자열은 임의적으로 값객체로 정의 Mutuable( 참조객체 ) : 변수에 저장된 것은 객체의 요소 ( 값 ) 들이 저장된 참조이므로 실제 값들이 변경이 가능 - 함수 파라미터 , 할당을 할 경우 참조만 넘어가므로 요소들이 변경이 가능

Page 267: 파이썬정리 20160130

객체 값 처리하는 예시

a = 10 # 10 이라는 숫자 객체 생김 참조가 생성Print(id(a)) # 변수 내의 10 숫자 객체의 참조 저장 # 1234567def aa(a) : aa = locals() print(aa[‘a’]) # 10 print(id(aa[‘a’])) # 1234567

aa(a) # 글로벌 a 변수를 aa 함수에 로컬변수로 할 # 당

변경불가능한 숫자 객체는 동일한 참조를 가지지만 변경이 불가능하기 때문에 call by Value 처럼 처리가 된다 .숫자 객체가 생성되면 어디서나 동일한 참조를 통해 처리한다 .

Page 268: 파이썬정리 20160130

Object Value Bound/unbound

명시적으로 Binding 을 처리할 것인지 실행시 Binding 을 처리할지 명확히 구분되어야 한다 .

Unbinding – List comprehension - range(), eval(), exec() 함수 - 함수의 가변인자 ( *args, ** args) - 인스턴스 메소드 , 클래스 메소드를 정의 없이 실행 시 binding - 인스턴스 객체에 속성이나 메소드 추가

Page 269: 파이썬정리 20160130

EXCEPTION

Page 270: 파이썬정리 20160130

Exception 처리 구문파이썬에서 예외가 발생할 경우 처리

try: Exception 을 발생시킬 문장 ...................... except ExceptionI: 해당 Exception 이 매칭될 경우 처리 except ExceptionII: 해당 Exception 이 매칭될 경우 처리...................... else: Exception 이 없을 경우 처리

Page 271: 파이썬정리 20160130

User Exception 처리User Exception 을 정의해서 다양한 세부 Excep-tion 추가하여 처리 가능

# 사용자 정의 Exception 타입 정의class Uexcept(Exception) : def __init__(self,ex_code,ex_err) : self.ex_code = ex_code self.ex_err = ex_err # Exception 발생 함수 정의def R_call() :

try: i = i + 1 except Exception as err : x = Uexcept("1111",err) print "ex coed ",x.ex_code print "ex_err ", x.ex_err raise x

# 실행try : R_call()except Uexcept as err : print err.ex_code print err.ex_err

# 처리 결과ex coed 1111ex_err local variable 'i' referenced before assign-ment1111local variable 'i' referenced before assignment

Page 272: 파이썬정리 20160130

Try-except-[else] 파이썬에서 예외가 발생할 경우를 처리하고 추가적으로 실행시킬 것이 있는 경우 else 처리

try: f = open('foo.txt', 'r')except FileNotFoundError as e: print(str(e))else: data = f.read() f.close()

else 는예외가 발생하지 않을 경우만 처리

Page 273: 파이썬정리 20160130

Try-[except]-finally파이썬에서 예외가 발생할 경우 except 처리하고finally 는 무조건 처리

try : R_call()except Uexcept as err : print err.ex_code print err.ex_errfinally : print "pass"

finally 는 예외 여부 상관없이 처리

Page 274: 파이썬정리 20160130

Exception 발생시 메시지처리Except 문장에서 발생된 메시지를 처리하기 위해 as 인스턴스 또는 , 인스턴스로 메시지를 처리

# 함수 정의def temp_convert(var): try: return int(var) #except ValueError , Argument : except ValueError as Argument: print Argument.message print "The argument does not contain numbers\n", Argument

# 함수 콜temp_convert("xyz");

# 처리 결과 invalid literal for int() with base 10: 'xyz'The argument does not contain numbersinvalid literal for int() with base 10: 'xyz‘

Page 275: 파이썬정리 20160130

Raising exception강제로 exception 을 발생시킬 경우 raise 문으로 exception 을 일으킴

# 함수 정의def get_age(): age = int(input("Please enter your age: ")) if age < 0: # Create a new instance of an exception my_error = ValueError("{0} is not a valid age".format(age)) # exception 발생 raise my_error return age

>>> get_age() Please enter your age: 42 42 >>> get_age() Please enter your age: -2 Traceback (most recent call last): File "<interactive input>", line 1, in <module> File "learn_exceptions.py", line 4, in get_age raise ValueError("{0} is not a valid age".format(age))ValueError: -2 is not a valid age

Page 276: 파이썬정리 20160130

Exception class 구조Exception 은 기본 args 와 massage 변수 존재

>>> a = Exception(' messsage ')>>> a.args(' messsage ',)>>> a.message' messsage '>>>

Page 277: 파이썬정리 20160130

내장 Exception(1) EXCEPTION NAME DESCRIPTION

Exception Base class for all exceptionsStopIteration Raised when the next() method of an iterator does not point to any object.SystemExit Raised by the sys.exit() function.

StandardError Base class for all built-in exceptions except StopIteration and SystemExit.ArithmeticError Base class for all errors that occur for numeric calculation.OverflowError Raised when a calculation exceeds maximum limit for a numeric type.

FloatingPointError Raised when a floating point calculation fails.ZeroDivisonError Raised when division or modulo by zero takes place for all numeric types.

AssertionError Raised in case of failure of the Assert statement.AttributeError Raised in case of failure of attribute reference or assignment.

EOFError Raised when there is no input from either the raw_input() or input() function and the end of file is reached.

ImportError Raised when an import statement fails.KeyboardInterrupt Raised when the user interrupts program execution, usually by pressing Ctrl+c.

LookupError Base class for all lookup errors.IndexErrorKeyError

Raised when an index is not found in a sequence.Raised when the specified key is not found in the dictionary.

Page 278: 파이썬정리 20160130

내장 Exception(2) EXCEPTION NAME DESCRIPTION

NameError Raised when an identifier is not found in the local or global namespace.

UnboundLocalErrorEnvironmentError

Raised when trying to access a local variable in a function or method but no value has been assigned to it.Base class for all exceptions that occur outside the Python environment.

IOError Raised when an input/ output operation fails, such as the print statement or the open() func-tion when trying to open a file that does not exist.Raised for operating system-related errors.

SyntaxErrorIndentationError

Raised when there is an error in Python syntax.Raised when indentation is not specified properly.

SystemError Raised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit.

SystemExit Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit.

ValueError Raised when the built-in function for a data type has the valid type of arguments, but the ar-guments have invalid values specified.

RuntimeError Raised when a generated error does not fall into any category.

NotImplementedError Raised when an abstract method that needs to be implemented in an inherited class is not actually implemented.

Page 279: 파이썬정리 20160130

Traceback 모듈 이용하기 Exception 을 처리하면 Traceback 부분을 가져올 수 없지만 Traceback 출력이 필요한 경우 print 하여 볼 수 있다 .

import traceback

try: 1/0except Exception: print 'the relevant part is: '+ traceback.format_exc()

# Exception 만 처리시는 Traceback 부분이 제외됨 print "exception print : " + e.message

# 처리결과the relevant part is: Traceback (most recent call last): File "C:/myPython/myproject/traceback_test.py", line 35, in <module> 1/0ZeroDivisionError: integer division or mod-ulo by zero

exception print : integer division or modulo by zero

Page 280: 파이썬정리 20160130

PYTHON FILE 처리

Page 281: 파이썬정리 20160130

File 은 Object파일도 하나의 Object 로 구현되어 있어 File 처리를 할 때 메소드를 이용하여 처리할 수 있도록 구성되어 있다 .파일은 라인이라는 요소들로 구성된 하나의 객체이므로 iterable 처리가 가능

참조 Container

Line 참조Line 참조Line 참조

……

Line 값Line 값Line 값……

Page 282: 파이썬정리 20160130

File 은 Object Method(1)

Method 설명file.close() Close the file

file.flush() 내부 버퍼에 있는 내용을 파일에 저장file.fileno() Return the integer “file descriptor” that is used by the underlying im-

plementation to request I/O operations from the operating system

file.isatty() Return True if the file is connected to a tty(-like) device, else False.

file.next()A file object is its own iterator, for example iter(f) returns f (unless f is closed). When a file is used as an iterator, typically in a for loop (for ex-ample, for line in f: print line.strip()), the next() method is called repeat-edly.

file.read([size]) Read at most size bytes from the file (less if the read hits EOF before ob-taining size bytes).

file.readline([size]) Read one entire line from the file. 

file.readlines([sizehint]) 파일 전체를 라인 단위로 끊어서 리스트에 저장한다 ..

Page 283: 파이썬정리 20160130

File 은 Object Method(2)

Method 설명file.xreadlines() 파일 전체를 한꺼번에 읽지는 않고 , 필요할 때만 읽는다 .

file.seek(offset[, whence])

파일의 위치 이동 .(whence 가 없으면 처음에서 offset 번째로 , 1 이면 현재에서 offset 번째로 , 2 이면 마지막에서 offset 번째로 )  - seek(n) : 파일의 n 번째 바이트로 이동 - seek(n, 1) : 현재 위치에서 n 바이트 이동 (n 이 양수이면 뒤쪽으로 , 음수이면 앞쪽으로 이동 )  - seek(n, 2) : 맨 마지막에서 n 바이트 이동 (n 은 보통 음수 )

file.tell() 현재의 파일 포인터 위치를 돌려줌 .

file.truncate([size]) 파일 크기를 지정된 잘라 버림 . 인수를 주지 않으면 현재 위치에서 자름 .. 

file.write(str) Write a string to the file. There is no return value. 

file.writelines(sequence) 리스트 안에 있는 문자열을 연속해서 출력함 .

Page 284: 파이썬정리 20160130

File 은 Object Variable

Method 설명file.closed bool indicating the current state of the file object. 

file.encoding The encoding that this file uses.

file.errors The Unicode error handler used along with the encoding.

file.mode The I/O mode for the file. If the file was created using the open() built-in function, this will be the value of the mode parameter.

file.nameIf the file object was created using open(), the name of the file. Other-wise, some string that indicates the source of the file object, of the form <...>.

file.newlinesIf Python was built with universal newlines enabled (the default) this read-only attribute exists, and for files opened in universal newline read mode it keeps track of the types of newlines encountered while reading the file.

file.softspace oolean that indicates whether a space character needs to be printed be-fore another value when using the print statement.

Page 285: 파이썬정리 20160130

File 생성 및 닫기파일 생성 파일 열기 및 생성 : 파일객체 = open( 파일이름 , 파일열기모드 ) 파일 닫기 : 파일객체 .close()

f = open("newfile.txt", 'w') f.close()

현재 디렉토리에 newfile.txt 가 생성

Page 286: 파이썬정리 20160130

File 열기모드파일열기모드 설명

r 읽기모드 - 파일을 읽기만 할 때 사용r+ 읽고쓰기모드 - 파일에 내용을 읽고 쓸 때 사용a 추가모드 - 파일의 마지막에 새로운 내용을 추가 시킬 때 사용 ( 쓰기전용 )

a+ 파일 끝에 추가 ( 읽기도 가능 )

w 쓰기모드 - 파일에 내용을 쓸 때 사용w+ 읽고 쓰기 ( 기존 파일 삭제 )

t 텍스트모드 – 기본 텍스트b 바이너리모드 - 바이너리로 처리rb 이진 파일 읽기 전용

rb+ 이진 파일 읽고 쓰기wb+ 이진 파일 읽고 쓰기 ( 기존 파일 삭제 )

ab+ 이진 파일 끝에 추가 ( 읽기도 가능 )

Page 287: 파이썬정리 20160130

File 생성 및 닫기 – with 문With 문은 파일을 열고 닫는 것을 자동으로 해 줄 수 있다면 편리하기 위해서 사용

f = open(“withfile.txt", 'w') f.write(“Hello World !!!!") f.close()

With 문을 사용하면 file.close() 를 사용하지 않아도 with 문 내문에서 처리한 것이 완료되면 file 이 자동으로 close 됨with open(" withfile.txt", "w") as f: f.write(" Hello World !!!!")

Page 288: 파이썬정리 20160130

File 오픈 후 쓰기파일을 다시 오픈하고 파일객체 .write() 를 이용하여 파일에 쓰기

f = open("newfile.txt", 'w')

#for 문을 이용하여 10 라인 추가for i in range(1, 11): # 파일 라인에 출력 line = "%d 번째 줄입니다 .\n" % i f.write(line)

f.close()

현재 디렉토리에 newfile.txt 을 열고 10 라인 추가newfile.txt 을 열면 결과값은

1 번째 줄입니다 .2 번째 줄입니다 .3 번째 줄입니다 .4 번째 줄입니다 .5 번째 줄입니다 .6 번째 줄입니다 .7 번째 줄입니다 .8 번째 줄입니다 .9 번째 줄입니다 .10 번째 줄입니다 .

Page 289: 파이썬정리 20160130

File 오픈 후 추가하기w’ 모드로 파일을 연 경우에는 이미 존재하는 파일을 열 경우 그 파일의 내용이 모두 사라지게 된다파일을 다시 추가하려면 파일객체 = open( 파일이름 , “a”) 로 세팅하여 파일객체 .write() 를 이용하여 파일에 쓰기

f = open("newfile.txt", 'w')

for i in range(1, 11): # 파일 라인에 출력 line = "%d 번째 줄입니다 .\n" % i f.write(line)

f.close()

# 기존 파일에 추가모드로 세팅f = open("newfile.txt",'a')

for i in range(11, 21): data = "%d 번째 줄입니다 .\n" % i f.write(data)

f.close()

현재 디렉토리에 newfile.txt 을 열고 10 라인 추가하고 다시 오픈하여 20 라인까지 추가newfile.txt 을 열면 결과값은

1 번째 줄입니다 .2 번째 줄입니다 .3 번째 줄입니다 .4 번째 줄입니다 .5 번째 줄입니다 .6 번째 줄입니다 .7 번째 줄입니다 .8 번째 줄입니다 .9 번째 줄입니다 .10 번째 줄입니다 .11 번째 줄입니다 .12 번째 줄입니다 .13 번째 줄입니다 .14 번째 줄입니다 .15 번째 줄입니다 .16 번째 줄입니다 .17 번째 줄입니다 .18 번째 줄입니다 .19 번째 줄입니다 .20 번째 줄입니다 .

Page 290: 파이썬정리 20160130

File 오픈 후 읽기 - 한 라인파일을 다시 오픈하고 파일객체 .readline() 를 이용하여 파일을 읽기

# 읽기모드로 파일 읽기f = open("newfile.txt", 'r') # 파일에서 한 라인 읽기line = f.readline() print(line)

f.close()

현재 디렉토리에 newfile.txt 을 열고 출력값은

1 번째 줄입니다 .

Page 291: 파이썬정리 20160130

File 오픈 후 읽기 - 여러 라인파일을 다시 오픈하고 파일객체 .readline(), 파일객체 .readlines(), 파일객체 .read() 를 이용하여 파일을 읽기

f = open("newfile.txt", 'r')

while True: line = f.readline() if not line: break print(line)

f.close()

f = open("newfile.txt", 'r') data = f.read()

print(data)

f.close()

한줄씩 읽기 파일 읽고 iterable 이용

f = open("newfile.txt", 'r') data = f.read()

print(data)

f.close()

파일 전체 읽기

Page 292: 파이썬정리 20160130

직접 실행 함수들

Page 293: 파이썬정리 20160130

eval : Expression 실행Eval 함수는 컴파일 및 표현식을 평가하고 실행 처리

>>> eval("1+2")3>>>

Page 294: 파이썬정리 20160130

exec : Statement 실행Exec 함수는 컴파일하여 문장을 평가하고 실행하기

>>> exec('print "hello world"')hello world>>>

Page 295: 파이썬정리 20160130

Text 실행 Class 만들기 (1)문자열을 받아서 문장을 평가하고 실행하는 클래스를 만들고 인스턴스를 만들고 실행하기

class Sandbox(object): def execute(self, code_string): exec code_string s = Sandbox()code = """print "Hello world""""s.execute(code)

텍스트 즉 문자열을 받아서 문장을 실행# 결과값Hello world

Page 296: 파이썬정리 20160130

Text 실행 Class 만들기 (2)file, open, eval, exec 등 keyword 들 일부는 실행시킬 경우 자원낭비나 서비스상의 이슈가 발생할 수 있으므로 사용하지 않는다 .

class Sandbox(object): def execute(self, code_string): exec code_string code1 = """file("test.txt", "w").write("Kaboom!\\n")"""

s.execute(code1)

텍스트 즉 문자열을 받아서 문장을 실행# 결과값 test.txt 내에Kaboom!

Page 297: 파이썬정리 20160130

Text 실행 Class 만들기 (3)file, open, eval, exec 등 keyword 들 일부는 실행시킬 경우 실제 __builtins__ 에서 제공되는 함수를 이용하지 않아서 자원낭비나 서비스상의 이슈가 발생할 수 있으므로 사용하지 않는다 .

class Sandbox(object): def execute(self, code_string): keyword_blacklist = ["file", "open", "eval", "exec"] for keyword in keyword_blacklist: if keyword in code_string: raise ValueError("Blacklisted") exec code_string s = Sandbox()code = """print "Hello world""""s.execute(code)

code1 = """file("test.txt", "w").write("Kaboom!\\n")"""s.execute(code1)

텍스트 즉 문자열을 받아서 문장을 실행# 결과값Hello world

# 에러 발생ValueError: Blacklisted

Page 298: 파이썬정리 20160130

COMMAND 처리

Page 299: 파이썬정리 20160130

Command line실행창에서 직접 명령을 줘서 실행할 경우 파라미터 설명$ python –h # 파이썬 command help 메시지 처리usage: python [-BdEiOQsRStuUvVWxX3?] [-c command | -m module-name | script | - ] [args]

Option Description-d provide debug output-O generate optimized bytecode (resulting in .pyo files)

-S do not run import site to look for Python paths on startup

-v verbose output (detailed trace on import statements)

-X disable class-based built-in exceptions (just use strings); obsolete starting with version 1.6

-c cmd run Python script sent in as cmd string

file run Python script from given file

Page 300: 파이썬정리 20160130

Command line - 예시파이썬 모듈 직접 실행

$ python test.py arg1 arg2 arg3

#!/usr/bin/python import sys print 'Number of arguments:', len(sys.argv), 'argu-ments.' print 'Argument List:', str(sys.argv)

명령창에서 test.py 를 실행

test.py 작성

Sys 모듈의 argv 로 명령 내의 요소들과 연계됨sys.argv[1] 은 프로그램 모듈명이 됨

# 처리결과Number of arguments: 4 arguments.Argument List: ['test.py', 'arg1', 'arg2', 'arg3']

Page 301: 파이썬정리 20160130

PYTHON 모듈 설치

Page 302: 파이썬정리 20160130

PIP command 처리 Command 창에서 파이썬 모듈을 설치 및 삭제Pip <command> [options] [ 모듈명 ]

Page 303: 파이썬정리 20160130

PIP : 현재 설치된 모듈 조회C:\Python27\Lib\site-packages 내에 설치된 목록

Page 304: 파이썬정리 20160130

PIP : 새로운 모듈 설치flask 모듈 설치

Page 305: 파이썬정리 20160130

PYTHON RE 모듈정규식 사용하기

Page 306: 파이썬정리 20160130

정규표현식 정규표현식을 정의 : 문자열에 대한 표현을 메타문자로 표시함 정규표현식을 실행 : 실제 문자열을 넣고 정규식과 매칭여부 검증 정규표현식을 실행하는 방법은 함수를 이용하거나 컴파일을 이용해서 메소드를

호출하여 처리

Page 307: 파이썬정리 20160130

리터럴 단어 등을 직접 입력하여 정규표현식 매칭

Example Descriptionpython Match "python".

Page 308: 파이썬정리 20160130

문자클래스 (character class, [])

문자클래스를 만드는 메타문자인 [ 와 ]  사이에는 어떤 문자 사용 문자클래스로 만들어진 정규식은 "[ 과 ] 사이의 문자들과 매치 " 라는 의미

• [a-zA-Z]  : 알파벳 모두• [0-9]  : 숫자•  ^  메타문자는 반대 (not) 의 의미 :  [^0-9] 라는 정규표현식은 숫자가 아닌 문자만 매치

Example Description[Pp]ython Match "Python" or "python"rub[ye] Match "ruby" or "rube"[aeiou] Match any one lowercase vowel[0-9] Match any digit; same as [0123456789][a-z] Match any lowercase ASCII letter[A-Z] Match any uppercase ASCII letter[a-zA-Z0-9] Match any of the above[^aeiou] Match anything other than a lowercase vowel[^0-9] Match anything other than a digit

Page 309: 파이썬정리 20160130

축약형 문자표현 축약형 문자표현 대문자로 사용된것은 소문자의 반대임

\d - 숫자와 매치 , [0-9] 와 동일한 표현식 \D - 숫자가 아닌것과 매치 , [^0-9] 와 동일한 표현식 \s - whitespace 문자와 매치 , [ \t\n\r\f\v] 와 동일한 표현식이다 . 맨 앞의 빈칸은

공백문자 (space) 를 의미 \S - whitespace 문자가 아닌 것과 매치 , [^ \t\n\r\f\v] 와 동일한 표현식 \w - 문자 + 숫자 (alphanumeric) 와 매치 , [a-zA-Z0-9] 와 동일한 표현식 \W - alphanumeric 이 아닌 문자와 매치 , [^a-zA-Z0-9] 와 동일한 표현식

Page 310: 파이썬정리 20160130

축약형 문자표현 - 세부Pattern Description

\w Matches word characters.

\W Matches nonword characters.

\s Matches whitespace. Equivalent to [\t\n\r\f].

\S Matches nonwhitespace.

\d Matches digits. Equivalent to [0-9].

\D Matches nondigits.

\A Matches beginning of string.

\Z Matches end of string. If a newline exists, it matches just before newline.

\z Matches end of string.

\G Matches point where last match finished.

\b Matches word boundaries when outside brackets. Matches backspace (0x08) when inside brack-ets.

\B Matches nonword boundaries.

\n, \t, etc. Matches newlines, carriage returns, tabs, etc.

\1...\9 Matches nth grouped subexpression.

\10 Matches nth grouped subexpression if it matched already. Otherwise refers to the octal represen-tation of a character code.

Page 311: 파이썬정리 20160130

^ / $^ 문자열의 맨 처음과 일치함을 의미 컴파일 옵션 re.MULTILINE  을 사용할 경우에는 여러줄의 문자열에서는 각 라인의 처음과

일치 ^  문자를 메타문자가 아닌 문자 그 자체로 매치하고 싶은 경우에는 [^] 처럼 사용하거나

\^  로 사용

$  문자열의 맨 마지막부터 일치함을 의미 $  문자를 메타문자가 아닌 문자 그 자체로 매치하고 싶은 경우에는 [$]  처럼

사용하거나 \$  로 사용

Page 312: 파이썬정리 20160130

Anchor 처리 예시Example Description

^Python Match "Python" at the start of a string or internal line

Python$ Match "Python" at the end of a string or line

\APython Match "Python" at the start of a string

Python\Z Match "Python" at the end of a string

\bPython\b Match "Python" at a word boundary

\brub\B \B is nonword boundary: match "rub" in "rube" and "ruby" but not alone

Python(?=!) Match "Python", if followed by an exclamation point.

Python(?!!) Match "Python", if not followed by an exclamation point.

특정 위치를 고정하여 처리할 경우 사용

Page 313: 파이썬정리 20160130

DOT(.) dot(.) 메타문자는 줄바꿈 문자인 \n 를 제외한 모든 문자와 매치 re.DOTALL  이라는 옵션을 주면 \n 문자와도 매치의미

• a.b :  "a + 모든문자 + b“•  a[.]b : "a + Dot(.) 문자 + b"

Page 314: 파이썬정리 20160130

반복 (*) * 바로 앞에 있는 문자 a 가 0 부터 무한개 까지 반복될 수 있다는 의미

정규식 문자열 Match 여부 설명ca*t ct Yes "a" 가 0 번 반복되어 매치ca*t cat Yes "a" 가 0 번 이상 반복되어 매치

(1 번 반복 )

ca*t caaat Yes "a" 가 0 번 이상 반복되어 매치 (3 번 반복 )

Page 315: 파이썬정리 20160130

반복 (+) + 는 최소 1 개 이상의 반복을 필요로 하는 메타문자

정규식 문자열 Match 여부 설명ca+t ct No "a" 가 0 번 반복되어 매치되지

않음ca+t cat Yes "a" 가 1 번 이상 반복되어 매치

(1 번 반복 )

ca+t caaat Yes "a" 가 1 번 이상 반복되어 매치 (3 번 반복 )

Page 316: 파이썬정리 20160130

반복 (?) ?  메타문자가 의미하는 것은 {0, 1}

정규식 문자열 Match 여부 설명ab?c abc Yes "b" 가 1 번 사용되어 매치ab?c ac Yes "b" 가 0 번 사용되어 매치

Page 317: 파이썬정리 20160130

반복 ({m,n}) {}  메타문자를 이용하면 반복횟수를 고정시킬 수 있다 . {m, n}  정규식을

사용하면 반복횟수가 m 부터 n 인것을 매치 {1,} 은 + 와 동일하며 {0,} 은 * 와 동일

정규식 문자열 Match 여부 설명ca{2}t cat No "a" 가 1 번만 반복되어

매치되지 않음ca{2}t caat Yes "a" 가 2 번 반복되어 매치

ca{2,5}t cat No "a" 가 1 번만 반복되어 매치되지 않음

ca{2,5}t caat Yes "a" 가 2 번 반복되어 매치ca{2,5}t caaaaat Yes "a" 가 5 번 반복되어 매치

Page 318: 파이썬정리 20160130

백슬래시 (\) 문제 “\section” : 이 정규식은 \s  문자가 whitespace 로 해석되어 [ \t\n\r\f\

v]ection 동일한 의미 “\\section” : 파이썬 문자열 리터럴 규칙에 의하여 \ 이 \\ 로 변경

\\  문자를 전달하려면 파이썬은 \\\\  처럼 백슬래시를 4 개나 사용 r”\section” : Raw String 규칙에 의하여 백슬래시 두개 대신 한개만 써도

두개를 쓴것과 동일한 의미

Page 319: 파이썬정리 20160130

Alternatives (|,or) |  메타문자는 "or" 의 의미와 동일 A|B  라는 정규식이 있다면 이것은 A 또는 B 라는 의미

Example Descriptionpython|perl Match "python" or "perl"rub(y|le)) Match "ruby" or "ruble"Python(!+|\?) "Python" followed by one or more ! or one ?

Page 320: 파이썬정리 20160130

Grouping ( ) ( ) 내에 정규 표현식을 정의하고 특정 단어나 특정 그룹을 표시

Example Description(re) Groups regular expressions and remembers matched text.(?imx) Temporarily toggles on i, m, or x options within a regular expression. If

in parentheses, only that area is affected.(?-imx) Temporarily toggles off i, m, or x options within a regular expression. If

in parentheses, only that area is affected.(?: re) Groups regular expressions without remembering matched text.(?imx: re) Temporarily toggles on i, m, or x options within parentheses.(?-imx: re) Temporarily toggles off i, m, or x options within parentheses.(?#...) Comment.(?= re) Specifies position using a pattern. Doesn't have a range.(?! re) Specifies position using pattern negation. Doesn't have a range.(?> re) Matches independent pattern without backtracking.

Page 321: 파이썬정리 20160130

Grouping ( ) - 예시 line = "Cats are smarter than dogs“ matchObj = re.match( r'(.*) are (.*?) (.*)', line, re.M|re.I) Cats 는 (.*) 매칭 , smarter 는 (.*?) 와 매칭 , than dogs 는 (.*) 와 매칭 re.I - 대소문자에 관계없이 매치 , Re.m – 여러 줄과 매치

Example Description\D\d+ \DNo group: + repeats \d(\D\d)+ Grouped: + repeats \D\d pair([Pp]ython(, )?)+ Match "Python", "Python, python, python", etc.

Example Description([Pp])ython&\1ails Match python&pails or Python&Pails(['"])[^\1]*\1 Single or double-quoted string. \1 matches whatever the 1st group

matched. \2 matches whatever the 2nd group matched, etc.

기존 그룹을 재사용하기 기존 그룹을 숫자를 사용하여 참조하게 한다 .

Page 322: 파이썬정리 20160130

정규식 정의 및 실행  re 모듈은 파이썬이 설치될 때 자동으로 설치되는 기본 라이브러리 p = re.compile('ab*', re.IGNORECASE) : re.IGNORECASE 옵션이 의미하는

것은 대소문자를 구분하지 않음>>> import re>>> mat = re.compile("[a-z]+")>>> mat<_sre.SRE_Pattern object at 0x063D2C60>>>>

>>> m = re.match('[a-z]+', "python")>>> m.group()'python'>>> mo2 = re.match("[a-z]+","abc")>>> mo2.group()'abc'>>>

Comile() 함수를 사용하여 실행

함수를 이용한 모듈 단위로 수행 직접 re 패키지 내의 함수 (match() 함수 등 ) 를 사용하여 실행

Page 323: 파이썬정리 20160130

함수 : 문자열 검색 문자열에 패턴을 찾아 검색이 필요한 경우 처리 match, search 는 정규식과

매치될 때에는 match object 를 리턴하고 매치되지 않을 경우에는 None 을 리턴

함수 목적match( 패턴 , 문자열 , 플래그 ) 문자열의 처음부터 정규식과 매치되는지 조사한다 .search( 패턴 , 문자열 , 플래그 ) 문자열 전체를 검색하여 정규식과 매치되는지 조사한다 .

line = "Cats are smarter than dogs"matchObj = re.match( r'(.*) are (.*?) (.*)', line, re.M|re.I)

if matchObj:print "matchObj.group() : ", matchObj.group()print "matchObj.group(1) : ", matchObj.group(1)print "matchObj.group(2) : ", matchObj.group(2)print "matchObj.group(3) : ", matchObj.group(3)else:print "No match!!"

(.*) 패턴은 문자숫자가 연속(.*?) 패턴은 문자숫자가 연속된 것이 0 또는 1

Group( 숫자 ) 는 각 패턴매칭된 결과

Page 324: 파이썬정리 20160130

함수 : 문자열 수정 문자열에 패턴을 찾아 변경이 필요한 경우 처리 match, search 는 정규식과

매치될 때에는 match object 를 리턴하고 매치되지 않을 경우에는 None 을 리턴

함수 목적sub(pattern,replace,string) 정규식에 매칭되는 것을 변경 .

phone = "010-959-559 # This is Phone Number"# 주석제거num = re.sub(r'#.*$', "", phone)print "Phone Num : ", num# 숫자를 제외한 모든 문자 제거num = re.sub(r'\D', "", phone) print "Phone Num : ", num

패턴 #.*$ 는 # 으로 시작하는 모든 문자를 $( 문자열의 끝 )까지 매칭패턴 \D 는 [^0-9] 즉 숫자가 아닌 문자를 매칭

Page 325: 파이썬정리 20160130

함수 :Greedy vs Non-Greedy

문자열에 패턴을 찾아 변경이 필요한 경우 처리 match, search 는 정규식과 매치될 때에는 match object 를 리턴하고 매치되지 않을 경우에는 None 을 리턴

함수 목적sub(pattern,replace,string) 정규식에 매칭되는 것을 변경 .

s = '<html><head><title>Title</title>'print len(s)

print(re.match('<.*>', s).span())print(re.match('<.*>', s).group())

print(re.match('<.*?>', s).span())print(re.match('<.*?>', s).group())

<.*> 패턴은 모든 매칭을 다 처리해서 결과는 <html><head><title>Title</title>'

<.*?> 패턴 첫번째만 처리해서 결과는 <html>

Page 326: 파이썬정리 20160130

정규표현식 -Compile

정규표현식 패턴객체 생성한 후 매칭을 시키는 객체를 생성하여 처리하는 방법• Compile options

DOTALL, S - .  이 줄바꿈 문자를 포함하여 모든 문자 IGNORECASE, I - 대소문자에 관계없이 매치 MULTILINE, M – 여러 줄과 매치 (^, $  메타문자의 사용과 관계가 있는 옵션 ) VERBOSE, X - verbose 모드를 사용 ( 정규식을 보기 편하게 만들수 있고 주석 등을 사용 )

>>> re.compile('.*')<_sre.SRE_Pattern object at 0x064AB2A8>>>>

Page 327: 파이썬정리 20160130

Compile Options- DOTALL, S

.  메타문자는 줄바꿈 문자 (\n) 를 제외한 모든 문자와 매치되는 규칙이 있다 . 하지만 \n  문자도 포함하여 매치하고 싶은 경우에는 re.DOTALL  또는 re.S 옵션으로 정규식을 컴파일하면 된다 .

>>> SS = re.compile('.ake')>>> RR = SS.match('\nake')>>> RR>>> RR == NoneTrue \n 은 . 과 매치되지 않기 때문이다 . 이것이 가능하려면 다음과 같이 re.S  옵션을 사용해야 한다 .>>> SS = re.compile('.ake',re.S)>>> RR = SS.match('\nake')>>> RR == NoneFalse>>> RR.group()'\nake'>>>

Page 328: 파이썬정리 20160130

Compile Options-IGNORECASE, I

re.IGNORECASE  또는 re.I  는 대소문자 구분없이 매치를 수행하고자 할 경우에 사용하는 옵션이다 .

>>> II = re.compile('[a-z]+')>>> ii = II.match('Python')>>> ii == NoneTrue>>> [a-z]  정규식은 소문자만을 의미하지만 re.I  옵션에 의해서 대소문자에 관계없이 매치되게 된 것이다 .>>> II = re.compile('[a-z]+',re.I)>>> ii = II.match('Python')>>> ii == NoneFalse>>> ii.group()'Python'>>>

Page 329: 파이썬정리 20160130

Compile Options-MULTILINE, M

re.MULTILINE 또는 re.M 옵션은 메타문자인 ^, $ 와 연관되어 있는 옵션이다 . ^ 와 $ 의 의미는

^ - 문자열의 처음 , $ - 문자열의 마지막 ^python  인 경우 처음은 항상 "python" 으로 시작 ,  python$ 라면 마지막은 항상 "python" 으로 끝나야 매치

>>> MM = re.compile('^Hello\s\w+')>>> data = """Hello World... Hello Dahl... Hello Moon""">>> mm = MM.match(data)>>> mm.group()'Hello World'>>>

re.MULTILINE  옵션으로 인해 ^ 메타문자가 문자열 전체가 아닌 라인의 처음이라는 의미를 갖게 되어 다음과 같은 결과가 출력될 것이다 .>>> MM = re.compile('^Hello\s\w+',re.M)

>>> MM.findall(data)['Hello World', 'Hello Dahl', 'Hello Moon']

Page 330: 파이썬정리 20160130

Compile Options-VERBOSE, X

이해하기 어려운 정규식에 주석 또는 라인단위로 구분을 하여 표시할 수 있도록 처리

>>> charref = re.compile(r'&[#](0[0-7]+|[0-9]+|x[0-9a-fA-F]+);')

첫번째와 두번째의 컴파일된 패턴 객체는 모두 동일한 역할을 한다 .

하지만 정규식이 복잡할 경우 두번째 처럼 주석을 적고 여러줄로 표현하는 것이 훨씬 가독성이 좋다는 것을 알 수 있을 것이다 .

re.VERBOSE  옵션을 사용하면 문자열에 사용된 whitespace 는 컴파일 시 제거된다 . ( 단 [] 내에 사용된 whitespace 는 제외 )

그리고 라인단위로 #  을 이용하여 주석문을 작성하는 것이 가능하게 된다 .

>>> charref = re.compile(r""" &[#] # Start of a numeric entity reference ( 0[0-7]+ # Octal form | [0-9]+ # Decimal form | x[0-9a-fA-F]+ # Hexadec-imal form ) ; # Trailing semicolon """, re.VERBOSE)

Page 331: 파이썬정리 20160130

정규표현식 – Compile 후 검색 match, search 는 정규식과 매치될 때에는 match object 를 리턴하고 매치되지 않을 경우에는 None

을 리턴 match - 문자열의 처음부터 검색 search – 문자열 내에서 일치하는 것이 있는지 검색

Method 목적match() 문자열의 처음부터 정규식과 매치되는지 조사한다 .search() 문자열 전체를 검색하여 정규식과 매치되는지 조사한다 .findall() 정규식과 매치되는 모든 라인의 문자열 (substring) 을 리스트로 리턴한다finditer() 정규식과 매치되는 모든 라인의 문자열 (substring) 을 iterator 객체로 리턴한다

Parameter Description

pattern 정규표현식string 패턴매칭될 문자열flags 패턴 매칭할 때 필요한 컴파일 options 들로 or(|) 연산자로 묶어서 표현

Page 332: 파이썬정리 20160130

match – match object Match 는 첫번째 자리부터 동일한 패턴이 발생할 때만 Object 가 만들어 짐 Match() 메소드에서 리턴하는 객체를 이용해서 메소드를 가지고 확인

Method 목적group() 매치된 문자열을 리턴한다 .

start() 매치된 문자열의 시작 위치를 리턴한다 .

end() 매치된 문자열의 끝 위치를 리턴한다 .

span() 매치된 문자열의 ( 시작 , 끝 ) 에 해당되는 튜플을 리턴한다

>>> mat = re.compile("[a-z]+")>>> mat<_sre.SRE_Pattern object at 0x063D2C60>>>> >>> mo = mat.match('abc')>>> mo<_sre.SRE_Match object at 0x065567C8>>>> >>> mo.group()'abc'>>> >>> mo.start()0>>> mo.end()3>>> mo.span()(0, 3)>>> # 동일한 패턴이 아니면 미스매칭>>> if mat.match(" abc") == None :... print("mismatch")... mismatch

Page 333: 파이썬정리 20160130

search – match object 내부에 있는 패턴을 검색하여 처음부터 매칭되는 것을 검색하여 매칭시킴

Method 목적group() 매치된 문자열을 리턴한다 .

start() 매치된 문자열의 시작 위치를 리턴한다 .

end() 매치된 문자열의 끝 위치를 리턴한다 .

span() 매치된 문자열의 ( 시작 , 끝 ) 에 해당되는 튜플을 리턴한다

>>> mat = re.compile("[a-z]+")>>> mat<_sre.SRE_Pattern object at 0x063D2C60>>>> >>> so1 = mat.search("123abc")>>> so1<_sre.SRE_Match object at 0x06556608>>>> so1.group()'abc'>>> so1.start()3>>> so1.end()6>>> so1.span()(3, 6)>>>

Page 334: 파이썬정리 20160130

search – match object 내부에 있는 패턴을 검색하여 처음부터 매칭되는 것을 검색하여 매칭시킴

Method 목적group() 매치된 문자열을 리턴한다 .

start() 매치된 문자열의 시작 위치를 리턴한다 .

end() 매치된 문자열의 끝 위치를 리턴한다 .

span() 매치된 문자열의 ( 시작 , 끝 ) 에 해당되는 튜플을 리턴한다

>>> mat = re.compile("[a-z]+")>>> mat<_sre.SRE_Pattern object at 0x063D2C60>>>> >>> so1 = mat.search("123abc")>>> so1<_sre.SRE_Match object at 0x06556608>>>> so1.group()'abc'>>> so1.start()3>>> so1.end()6>>> so1.span()(3, 6)>>>

Page 335: 파이썬정리 20160130

정규식 처리하기 (1/2)1. 정규식 객체 생성

>>> import re>>> p = re.compile("[a-zA-Z0-9]+")>>> p<_sre.SRE_Pattern object at 0x06506570>>>> p.__class__<type '_sre.SRE_Pattern'>>>> p.__class__.__name__'SRE_Pattern'>>>

2. 정규식 패턴 매칭을 위한 Match object 생성>>> m = p.match("python")>>> m<_sre.SRE_Match object at 0x06556AA0>>>> m.__class__.__name__'SRE_Match'>>>

Page 336: 파이썬정리 20160130

정규식 처리하기 (2/2)3. 정규식 패턴 매칭 결과를 확인

>>> m.group()'python'>>> m.span()(0, 6)>>>

Page 337: 파이썬정리 20160130

PICKLE 모듈 처리

Page 338: 파이썬정리 20160130

Pickle 로 특정객체 저장 및 호출 파이썬은 pickle 이라고 불리우는 기본 모듈을 제공어떤 파이썬 객체이든지 파일로 저장해 두었다가 나중에 불러와서 사용객체를 영구히 저장 필요시 사용

import pickle

# 객체 저장장소 이름 정의shoplistfile = 'shoplist.data‘

# 저장대상 객체 생성shoplist = ['apple', 'mango', 'carrot']# 객체 저장장소 파일로 생성f = open(shoplistfile, 'wb')

# 파일저장소에 저장pickle.dump(shoplist, f)f.close()

# 객체 삭제del shoplist

# 객제 저장 파일 읽기f = open(shoplistfile, 'rb')

# 저장된 파일을 로드storedlist = pickle.load(f)

print storedlist

Page 339: 파이썬정리 20160130

PYTHON OS 모듈

Page 340: 파이썬정리 20160130

OS 모듈 : OS 정보현재 사용 기기의 OS 정보

>>> import os>>> # 현재 OS 정보>>> os.name'nt'>>>

Page 341: 파이썬정리 20160130

OS 모듈 : 현재 directory 조회OS 내의 디렉토리 정보를 조회하거나 디렉토리 내의 정보를 조회하는 방법

>>> import os>>> # 현재 디렉토리>>> os.getcwd()'C:\\myPython\\myproject‘>>> # 현재 디렉토리>>> os.path.abspath('.')'C:\\myPython\\myproject‘>>> # 상위 디렉토리>>> os.path.abspath('..')'C:\\myPython'>>> # 디렉토리 내에 생성된 정보를 조회>>> os.listdir('.')['.spyderproject', '.spyderworkspace', 'aaa.txt', 'abc.txt‘]

Page 342: 파이썬정리 20160130

OS 모듈 : directory 이동OS 내의 디렉토리간 이동을 처리

>>> os.getcwd()'C:\\myPython\\myproject'>>> os.chdir('../kakao')>>> os.getcwd()'C:\\myPython\\kakao'>>>

Page 343: 파이썬정리 20160130

PYTHON SYS 모듈

Page 344: 파이썬정리 20160130

SYS 모듈 : 현재 파이썬 정보현재 사용 기기의 Python 정보

>>> import sys>>> sys.version'2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)]‘>>> sys.version_infosys.version_info(major=2, minor=7, micro=5, releaselevel='final', serial=0)

Page 345: 파이썬정리 20160130

SYS 모듈 : Command-line arguments

Sys 의 arguments 는 command window 내의 모듈명부터 인식함 .

import sys

# command line arg 출력print sys.argv

# command line arg 를 나눠서 출력for i in range(len(sys.argv)): if i == 0: print "Function name: %s" % sys.argv[0] else: print "%d. argument: %s" % (i,sys.argv[i])

C:\myPython\myproject>python sys_com.py arg1 arg2['sys_com.py', 'arg1', 'arg2']Function name: sys_com.py1. argument: arg12. argument: arg2

C:\myPython\myproject>python sys_com.py ['sys_com.py']Function name: sys_com.py

Sys_com.py 생성 Command window 에서 실행

Page 346: 파이썬정리 20160130

SYS 모듈 : ide 에서 arg 처리Dispalyhook 는 callable 객체 즉 함수나 메소드를 연결하여 arg 와 동일한 변수를 처리

>>> import sys>>> #arg 정의>>> v = (10,10)>>> # 함수정의>>> def add(v) :... print v[0]+ v[1]... >>> # 함수를 연결>>> sys.displayhook = add>>> #arg 실행하면 실제 연결된 함수 실행>>> v20>>>

help() 이용하여 모듈 정보 검색Sys.displayhook 함수를 이용

Page 347: 파이썬정리 20160130

SYS 모듈 : Command -input 사용 (1)

Command 창에서 입력을 받아 처리하기 .입력은 모두 string 으로 처리됨

# add_test.py 저장import syswhile True: # 3.0 버전부터 # s = input(‘Enter something :’) s = raw_input('Enter something : ') if s == 'quit': break print 'Length of the string is', len(s) print 'string ', s print 'Done

#command line 에서 입력 C:\myPython\myproject> python add_test.py10Quit# 처리결과Enter something : Length of the string is 2string 10Enter something : Done

Page 348: 파이썬정리 20160130

SYS 모듈 : Command -input 사용 (2)

Text File 에 저장해서 Command 창에서 실행 처리 .입력은 모두 string 으로 처리됨

# add_test.py 저장import syswhile True: # 3.0 버전부터 # s = input(‘Enter something :’) s = raw_input('Enter something : ') if s == 'quit': break print 'Length of the string is', len(s) print 'string ', s print 'Done

#add_test.txt. 에서 입력 10Quit

#command line 에서 입력 C:\myPython\myproject> python add_test.py < add_test.txt

# 처리결과Enter something : Length of the string is 2string 10Enter something : Done

Page 349: 파이썬정리 20160130

SYS 모듈 : ide-input 사용ide 창에서 입력을 받아 처리하기 .입력은 모두 string 으로 처리됨

# add_test.py 저장import syswhile True: # 3.0 버전부터 # s = input(‘Enter something :’) s = raw_input('Enter something : ') if s == 'quit': break print 'Length of the string is', len(s) print 'string ', s print 'Done

#ide 창 처리#ide 창에 10 입력Enter something : 10Length of the string is 2string 10#ide 창에 quit 입력Enter something : quitDone