python 정리

116
Python 강강강

Upload: uichanluke-kang

Post on 11-Apr-2017

62 views

Category:

Internet


2 download

TRANSCRIPT

Page 1: Python 정리

Python

강의찬

Page 2: Python 정리

목차

1. Python의 특징- coding rules

2. Variables, Expressions, and Statement3. Object

- 기본 자료형- 복합 자료형- 논리형

4. Statement- 조건문- 반복문- 탈출문

5. Function6. Class7. Exception8. Module9. FILE I/O10. Case Study

Page 3: Python 정리

1. Python 의 특징

Page 4: Python 정리

Python 언어의 특징

1) 가독성 우수- 문법이 간결하고 , 들여쓰기로 코드 구분

2) 풍부한 라이브러리3) 접착성

- C 언어와 교류 가능4) 유니코드

- 문자열이 모두 유니코드5) 동적 타이핑

- Dynamic Language, Interpreted Language

Page 5: Python 정리

Coding rules

1) PEP 8- 코드 4 칸 들여쓰기 (Tab)- 한줄 79 까지- 탑레벨 함수와 클래스 정의는 2

줄 띄기- 메서드 정의는 1 줄 띄기

2) 공백 사용 X- [] () 안- , : ; 앞에

3) 변수명- 숫자 , 문자 , _ 사용- 숫자로 시작 X- _ 변수 : 내부 변수 사용 시- 변수 _ : 키워드를 변수로 사용

시- __ 변수 __ 클래스 속성으로 용

4) 클래스명- CamelCase

5) 함수명- 소문자 , _ 로 구분

6) 주석- #

Page 6: Python 정리

2. Variables, Expressions, and Statement

Page 7: Python 정리

Variable

0

변수 - 객체를 가리키는 주소값을 저장하는 메모리 공간 - 변수에 객체가 바인딩 된다고 표현 - reference = 주소값del 변수명 , del( 변수명 ) 으로 삭제 가능

>>>x=10>>>id(x)1695346768

>>>x=20>>>id(x)1695347088

>>>y=30>>>id(y)1695347408

x

x

y

10

20

30

1695346768

1695347088

1695347408

Page 8: Python 정리

Variable

FalseNoneTrueandasassertbreakclasscontinue

defelifelseexceptfinallyforfromglobalif

importinislambdanonlocalnotorpassraise

returntrywhilewithyield

변수명은 문자 , 숫자 _ 사용 가능숫자로 시작 불가

Python keyword 는 변수명으로 사용할 수 없다 .

Page 9: Python 정리

식별자

_ 변수 : 내부 변수 , private변수 _ : 키워드 충돌 방지__ 변수 : 클래스 속성 , stronger private__ 변수 __ : magical

Page 10: Python 정리

데이터 은닉 : _ 변수 and __ 변수

.

2) __ 변수 : strong private - 클래스 밖에서 접근할 수 없음 - private 하게 만드려는 것이 아니라 , 클래스 내부의 다른 클래스와 충돌을 피하게 하기 위한 목적

1) _ 변수 : weakly private - 내부 변수이지만 , 외부 코드가 접근할 수 있음 - 하지만 , import 모듈명 import * 했을 때 , 해당 변수를

사용할 수 없음

Page 11: Python 정리

_ 변수

class Person: def __init__(self, name, contents): self.name=name self._secretlist=list(contents) def add_secret(self, story): self._secretlist.append(story)

myself=Person(" 김하나 ", [])myself.add_secret(" 짝사랑 ")myself.add_secret(" 학점 ")print(myself._secretlist) # 외부에서도 접근가능 [' 짝사랑 ', ' 학점 ']

Page 12: Python 정리

__ 변수

class Memory: __badmemory=" 학사경고 " def show_my_memory(self): print(self.__badmemory) past=Memory()past.show_my_memory() # 클래스 내부 메서드로 접근 가능print(past._Memory__badmemory) # _ 클래스명 __ 변수로

접근 가능print(past.__badmemory) # 객체명만으로는 접근 불가

<<<

학사경고학사경고AttributeError:

'Memory' object has no attribute '__badmemory'

Page 13: Python 정리

shallow copy & deep copyimport copya=[[1,2], [3,4], [5,6]]b=ac=copy.copy(a)d=copy.deepcopy(a)

print(a,b,c,d)

a[0]=100print(a,b,c,d)

a[1][0]=200print(a,b,c,d)

[[1, 2], [3, 4], [5, 6]][[1, 2], [3, 4], [5, 6]][[1, 2], [3, 4], [5, 6]][[1, 2], [3, 4], [5, 6]] 모두 똑같은 모양

[100, [3, 4], [5, 6]][100, [3, 4], [5, 6]][[1, 2], [3, 4], [5, 6[[1, 2], [3, 4], [5, 6]]같은 주소값을 공유하는 b 만 바뀐다 .

[100, [200, 4], [5, 6]][100, [200, 4], [5, 6]][[1, 2], [200, 4], [5, 6]][[1, 2], [3, 4], [5, 6]] 같은 주소값을 공유하는 b 가 바뀌고 , shallow copy 한

Page 14: Python 정리

Expression and Statement

0

>>>1010>>>n20

>>>n+3050

표현식은 값 , 변수 , 연산자의 혼합

# 할당>>>n=10>>>print(n)

문 (statement) 은 실행하는 코드

Page 15: Python 정리

Operation 순서

Parentheses : (1+2)*3 = 9 Exponentiation : 1+2**3 = 9, 2*3**2 = 18MultiplicationDivisionAdditionSubtraction

PEMDAS

Page 16: Python 정리

Operator 종류

사칙 연산자 : +, -, *, /, %논리 연산자 : &,| and, or - short circuit비교 연산자 : ==, !=, <, >, >=, <=

* isinstance( 객체 , 클래스 ) : 해당 객체가 해당 클래스의 인스턴스인지 확인ex) if isinstance(cust, VIPCustomer): True or False 반환

Page 17: Python 정리

3. Object

Page 18: Python 정리

Object

최상위 객체는 Object 이며 , 모든 객체를 Object Instance 로 처리

Object classAnimal

classCat

>>>print(isinstance(1, object))True# 정수 1 도 object 의 객체

Page 19: Python 정리

Data types : Type 클래스 객체를 상속 받음

기본 자료형

• Int : 4byte• Float : 4byte• Str : '' or "" - 이스케이프 문자

집합 자료형

• List : [] - index• Tuple : () - 수정 불가• Dictionary : {} - {key:value}• Set : {}

* {} 사용 1 순위는 dictionary

논리형

• Boolean - True - False : False,

None, 0, 0.0, (), {}, [], “”

\n 개행 ( 줄바꿈 )\t 탭\r 캐리지리턴( 커서 맨 앞으로 이동 )\s space\\ 문자 \\' 단일인용부호\" 다중인용부호

Page 20: Python 정리

immutable vs Mutabeimmutable

• int : 정수• float : 부동소수점• complex : 복소수

• str : 문자열• tuple : 튜플

mutable

• list : 리스트• dict : 딕셔너리• set : 세트

Page 21: Python 정리

Type Conversion

• int()• float()• str()• list(• tuple()• dict()• set()

Page 22: Python 정리

Numeric Type operator

• +, -, *, /• // 몫• % 나머지• x**y• abs() 절대값• divmod(x,y) 몫과 나머지• pow(x,y) 제곱

Page 23: Python 정리

Sequence Type : str, list, tuplesequence type 기본 처리 operator

• x in s• x not in s• s+t• n*s, s*n• s[index]• s[from:to]• s[from:to:by]• len(s)• min(s)• max(s)

유무 판단

concatenate반복index 번째 슬라이스슬라이스 , 공차길이최소최대

Page 24: Python 정리

Sequence slicing

0

my_string[from:to:by]from 을 포함해서 , to 를 제외하고 , by 만큼

Thank you0 1 2 3 4 5 6 7 8-9 -8 -7 -6 -5 -4 -3 -2 -1

Page 25: Python 정리

Sequence slicingmy_string="Thank you"

print(my_string[:])

print(my_string[0:7])

print(my_string[-1:])

print(my_string[-1:-7:-1])

# 전체표현Thank you# 0 에서 7 번째 전까지Thank y# 역순u# 역순uoy kn

Page 26: Python 정리

문자열 split()cust_info=" 이름 : 유현민 나이 :40 주소 : 관악구 "print(cust_info.split(' ')[0])

for data in cust_info.split(" "): print(data)

이름 : 유현민

이름 : 유현민나이 :40주소 : 관악구

Page 27: Python 정리

formatting

2) formatting operation : format()

1) format operator : % %s : 문자열 %d : 정수 (%.2d, %.3d 는 자릿수 올림 ) %g : 부동소수점

Page 28: Python 정리

format operator : %print("%s 씨는 %d 세입니다 ." %(" 유재명 ", 40))

print(" 오늘의 %s 는 %d%% 입니다 ." %(" 금리 ", 3.2))

print(" 오늘의 %s 는 %g%% 입니다 ." %(" 금리 ", 3.2))

print(" 오늘의 %s 는 %.3d%% 입니다 ." %(" 금리 ", 3.2))

유재명씨는 40 세입니다 .

오늘의 금리는 3% 입니다 .오늘의 금리는 3.2%

입니다 .오늘의 금리는 003%

입니다 .

Page 29: Python 정리

formatting operation : format()print(" 오늘의 {0} 는 {1}% 입니다 .".format(" 금리 ",

3.2))print("{1}% 는 오늘의 {0} 입니다 .".format(" 금리 ", 3.2))

오늘의 금리는 3.2% 입니다 .3.2% 는 오늘의 금리입니다 .

Page 30: Python 정리

내장 함수 : enumerate()list_=["first", "second", "third"]for i, v in enumerate(list_): print(i,v)

0 first1 second2 third

Page 31: Python 정리

내장 함수 : zip()list1=[1,2,3,4]list2=["one","two","three","four"]for k, v in zip(list1, list2): print(k,v)

1 one2 two3 three4 four

Page 32: Python 정리

내장 함수 : reversed()for i in reversed(range(1,10,2)): print(i)

97531

Page 33: Python 정리

내장 함수 : sorted()color_list=["blue", "white", "red", "orange"]

for i in sorted(color_list): print(i)

blueorangeredwhite

Page 34: Python 정리

list : basic method• list=[1,2,3]• len(list)• list.append(4)• del list[3]• ["hi"]*2

[1,2,3]3[1,2,3,4][1,2,3]["hi", "hi"]

Page 35: Python 정리

list : expressiona=[1,2,3]b=[10,100,1000]mul=[x*y for x in a for y in b] print(mul) [10, 100, 1000,

20, 200, 2000, 30, 300, 3000]

Page 36: Python 정리

tuple : basic method• tuple=(1,2,3)• len(tuple)• ("hi")*2

(1,2,3)3"hihi"

Page 37: Python 정리

set 설명

• set={}• 순서 없음 , 중복 불가• & 는 a.intersection(b)• | 는 a.union(b) • - 는 a.difference(b)• ^ 는 a.symmetric_difference(b)• <= 는 a.issubset(b)

교집합합집합차집합배타적 교집합부분집합

Page 38: Python 정리

map(dictionary) 설명

• key: value 쌍• {"key":"value"}• for k, v in 객체명 .items():• for item in 객체명 .items():

k 만 쓰면 , 튜플로 반환

item: ( 값 , 값 )

Page 39: Python 정리

map basic methoddict={"name":"kim", "age":20}dict["gender"]="female"

dict={"name":"kim", "age":20, "gender":"female"}

del dict["age"]dict={"name":"kim", "gender":"female"}

dict.clear()del dict

dict={key:value}새로운 key 할당

pair 삭제

모든 원소 삭제dict 자체 삭제

Page 40: Python 정리

mapuser = {"user" : "Ben","category" : "Literature","upload_times" : 19,"hashtags" : ["#books", "#korea", "#sharing",

"#awesome", "#sunny"]}

user_keys = user.keys() # list of keysuser_values = user.values() # list of valuesuser_items = user.items() # list of (key, value)

tuples

if "user" in user_keys: # True, slow

if "user" in user: # True: # faster

if "Ben" in user_values: # True

Page 41: Python 정리

4. Statement

Page 42: Python 정리

조건문

•if 문 if 조건식 : 구문

•if else 문 if 조건식 : 구문 else: if 안이 false 면 실행

•if elif else문 if 조건식: 구문 elif 조건식: 구문 else: false면 실행

Page 43: Python 정리

범위 조건식

def grade(jumsu): if jumsu >100: raise Exception(" 잘못된 점수입니다 .") elif 90<= jumsu <100: return "A" elif 80<= jumsu<90: return "B" elif 70<= jumsu < 80: return "C" else: return "F"; result=grade(1)print(result)

범위 조건식(Python 에서만 사용 )

Page 44: Python 정리

단축 평가

• x and y: x 가 False 인경우 , y 값은 평가하지 않음• x or y: x 가 True 인경우 , y 값은 평가하지 않음

Page 45: Python 정리

단축 평가

a=0b=2

if a and 10/a: print("a 가 0 입니다 .")else: print(" 정상 작동 -1")

if a and 10/b: print("a 는 0 입니다 .")else: print(" 정상 작동 -2")

if 10/b and a: print("a 가 0 입니다 .")else: print(" 정상 작동 -3") if 10/a and b: print("a 가 0 입니다 .")else: print(" 정상 작동 -4")

if b & 10/b: print("a 가 0 입니다 .")else: print(" 정상 작동 ")

정상 작동 -1 # 0 이 False 이기 때문에 , 뒤쪽 문을 실행하지 않고 바로 , else 로 넘어감

정상 작동 -2 # 0 이 False 이기 때문에 , 뒤쪽 문이 True 라도 , else 로 넘어감

정상 작동 -3

ZeroDivisionError: division by zero

TypeError: unsupported operand type(s) for &: 'int' and 'float'

Page 46: Python 정리

반복문

• for in 문 리스트 , 튜플 , 딕셔너리 자료구조와 사용 range() 이용해서 단순 반복• while 문

Page 47: Python 정리

for in : 별 lines=5for i in range(0, lines): for j in range(0, i+1): print("*", end='') print()

for i in range(0, lines): for j in range(0, lines-i): print("*", end='') print() for i in range(0, lines): for j in range(0, lines-i): print(' ', end='') for j in range(0, 2*i+1): print("*", end="") print()

***************

***************

* *** ***** ******* *********

Page 48: Python 정리

[ 표현식 for in 문 ]

L=[1,2,3,4,5]new_list=[2**i for i in L]print(new_list)

L2=["orange", "apple", "banana", "kiwi"]new_list=[i for i in L2 if len(i)>5]print(new_list)

L3=[1,2,3]L4=[3,5,7]new_list=[x*y for x in L3 for y in L4]print(new_list)

for 문은 i 를 뽑아오는 역할을 한다 .

[2,4,8,16,32]

['orange', 'banana']

[3, 5, 7, 6, 10, 14, 9, 15, 21]

Page 49: Python 정리

filter(func name, sequence object)L5=[10, 29, 39]IterList=filter(None, L5)for i in IterList: print("Item: {0}".format(i))

------------------------------------------------

def getBiggerThan20(i): return i >20

L5=[10, 29, 39]IterList=filter(getBiggerThan20, L5)for i in IterList: print("Item: {0}".format(i))

Item: 10Item: 29Item: 39

Item: 29Item: 39

Page 50: Python 정리

filter(func name, sequence object)

old_list=[10,20,30]new_list=old_listprint(old_list)new_list[0]=100print(new_list)print(old_list)

old_list=[10,20,30]new_list=list(filter(None, old_list))print(old_list)new_list[0]=100print(new_list)print(old_list)

[10, 20, 30]

[100, 20, 30][100, 20, 30]

# 함수실행 () 이 아니라 함수명을 넣어야 함

[10, 20, 30]

[100, 20, 30][10, 20, 30]

Page 51: Python 정리

map(func name, sequence object)L=[1,2,3]def add10(x): return x+10

print(list(map(add10, L)))print(list(map(lambda y:y+20, L)))

List1=[1,2,3]List2=[2,3,4]print(list(map(pow, List1, List2)))

List3=[4,5,6]def add(a,b,c): return a+b+cprint(list(map(add, List1, List2, List3)))print(list(map(lambda a,b,c: a+b+c, List1, List2,

List3)))

[11, 12, 13][21, 22, 23]

[1, 8, 81]

[7, 10, 13][7, 10, 13]

Page 52: Python 정리

lambda : 익명함수

L5=[10, 29, 39]print(list(filter(lambda i: i>20, L5)))

print((lambda x,y:x**2+5*x+4+y)(1,100))double=lambda x:x*2print(double(7))

[29, 39]

110

14

Page 53: Python 정리

반복문

• break : 반복문을 종료

• continue : 해당 반복을 skip

Page 54: Python 정리

5. Function

Page 55: Python 정리

함수 정의

- 함수 정의함수는 statement 처럼 실행되지만 , 그 효과는 함수 객체를 만드는 것 .함수 정의는 함수가 호출되기 전에 실행 (run) 되어야 한다 .

>>>def 함수명 (파라미터 ): # 함수 정의>>> statement>>>>>> 함수명 (인자 ) # 함수 호출

>>>def times(x,y):>>> return x*y>>>>>>times(5,10)

tiemsFunction Object

<0x0234A1237>이름이 객체의 레퍼런스

Page 56: Python 정리

__init__()class Person: name="디폴트 이름 " gender="디폴트 성별 " address="디폴트 주소 " def __init__(self, *param_): try: self.name=param_[0] self.gender=param_[1] self.address=param_[2] except: pass def print_info(self): print("info: {0}, {1}, {2}".format(self.name, self.gender,

self.address))

p1=Person(" 유재석 ", "남 ", "봉천 ")p2=Person("박명수 ")p3=Person()p1.print_info()p2.print_info()p3.print_info()

info: 유재석 , 남 , 봉천info: 박명수 , 디폴트 성별 , 디폴트

주소info: 디폴트 이름 , 디폴트 성별 ,

디폴트 주소

Page 57: Python 정리

return

-return 함수를 실행할 때 모든 함수 관련 리소스 ( 변수 포함 ) 를 스택에 저장 , return 시 스택에서 제거 다중값으로 전달 가능 (tuple 로 ) return 을 적지 않거나 , return 만 적었을 때도 함수가 종료 (None 객체 반환 )

Page 58: Python 정리

returndef swap(a,b): return b,a

x,y=swap(1,2)print(x)print(y)print(x,y)z=swap(1,2)print(z)

_,y=swap(1,2)print(_)

212 1

(2, 1) #tuple 로 반환

2 # 변수를 무시하고 싶을 때 _ 사용 , 값이 나오지 않는 것은 아님

Page 59: Python 정리

scoping rule

1) Local variable

2) Global variable

3) Built-in variable

LGB

Page 60: Python 정리

scoping rule

>>>x=10>>>def func(): x=20 print(x)>>>func()20>>>print(x)10

global : 함수 내부에서 전역 변수를 참조할 때

>>>x=10>>>def func(): global x x=20 print(x)>>>func()20>>>print(x)20

Page 61: Python 정리

*args and **kwargs

가변 인자 - * : tuple 로 전달 - ** : dictionary 로 전달printall(*args, **kwargs):

Page 62: Python 정리

* : asterisk operatordef add(a, b=10, *c): sum=0 for i in c: sum+=i return a+b+sum

print(add(10,20))print(add(10,20,30))print(add(10,20,30,40))print(add(10))print(add(b=10, a=20))

def add(a, b): return a+bdef add(a,b,c): return a+b+c

30601002030

# 파이썬은 메서드 중복을 허용하지 않음

# 중복을 허락 안 하기 떄문에 가변인자르 사용하자

# 파라미터 변수 앞에 *뿐이면 가변인자가 된다 .

# 함수 호출 시 인자 값이 함수 파라미터 c 에 튜플로 전달된다 .

Page 63: Python 정리

** : scatter operatordef user_url_builder(server, port, **user): str_="http://" + server + ":"+str(port)+"/?" for key in user.keys(): str_+=key+"="+user[key]+"&" return str_

print(user_url_builder("javaspecialist.co.kr", 80, id="idname", password="1313" ))

http://javaspecialist.co.kr:80/?id=idname&password=1313&

Page 64: Python 정리

lambda

lambda( 익명함수 ) - lambda 파라미터 : 구문 - ex) lambda x, y: x*y

Page 65: Python 정리

lambda 식 : 익명함수

g=lambda x: x**3print(g(2))

a=(lambda x, y: x+y)(10,100)print(a)

8

110

Page 66: Python 정리

iterator

iterator : 나열 객체 - iter() - next(interator) - iterator.__next__() - 객체를 소비 ( 사용 후 삭제 )

Page 67: Python 정리

iterator : 나열 객체

s="hello"it=iter(s)print(it)print(next(it))print(next(it))print(next(it))print(it.__next__())print(it.__next__())print(it.__next__()) # 에러 더 이상 데이터 없음

<str_iterator object at 0x000001C4AC803278>

helloStopIteration

Page 68: Python 정리

재귀함수

def factorial(x): if x==1: return 1 return x*factorial(x-1)

print(factorial(4))

recursive function

Page 69: Python 정리

help() : 도움말

help(print)

def add(a,b): return a+b

help(add)

add.__doc__="a 와 b 를 더합니다 ."

help(add)

print(...) print(value, ..., sep=' ',

end='\n', file=sys.stdout, flush=False)

Prints the values to a stream,

or to sys.stdout by default. Optional keyword arguments: file: a file-like object

(stream); defaults to the current sys.stdout.

sep: string inserted between values, default a space.

end: string appended after the last value, default a newline.

flush: whether to forcibly flush the stream.

Help on function add in module __main__:

add(a, b)

Help on function add in module __main__:

add(a, b) a와 b를 더합니다.

Page 70: Python 정리

함수결과 처리 : return and yieldreturn

• 함수의 실행 결과를 반환• return 사용하지 않으면 , None 반환

• 값을 여러 개 return 하면 , tuple 하나로 반환

yield

• 함수가 메모리에 남아서 , 재호출하면 next() 로 반환

Page 71: Python 정리

일반 함수 : returndef reverse1(data): for i in range(len(data)-1, -1, -1): return data[i] s1= "helloworld"print(reverse1(s1)) d

return 은 하나만 출력하고 , 함수를 멈춤

Page 72: Python 정리

generator : yield(1)def reverse2(data): for i in range(len(data)-1, -1, -

1): yield data[i] s2 = "helloworld"print(reverse2(s2))

yield 는 끝까지 출력dlrowolleh

Page 73: Python 정리

generator : yield(2)>>>def yrange(n): i = 0 while i < n: yield i i += 1>>> y = yrange(3) >>> y <generator object yrange at

0x401f30> >>> y.next()>>> y.next()>>> y.next()>>> y.next()

012Traceback (most

recent call last): File "<stdin>", line 1, in <module> StopIteration

Page 74: Python 정리

6. Class

Page 75: Python 정리

클래스 선언

클래스 정의- class : 객체를 만드는 type- class 도 객체로 인식

Page 76: Python 정리

Class

변수클래스 변수

class 클래스명 : count=0

인스턴스 변수생성자 아래 선언

생성자def __init__(self):

소멸자def __del__(self):

instance methoddef my_method(self):

상속을 구현하고 , 객체를 통해 실행

class method@classmethod def my_method(cls):객체를 생성하지 않고 , 사용 가능

static method@staticmethod def my_method():객체의 멤버에 영향을 받지 않고 , 단순 기능만 수행

Page 77: Python 정리

.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 78: Python 정리

상속

•다중 상속 가능 class 클래스명 ( 부모 1, 부모 2):•부모 메서드 호출 부모명 . 메소드명 (self):•재정의 (override) 부모의 메서드를 자식에서 다시 정의

Page 79: Python 정리

재정의 (overriding)

부모 클래스에서 사용된 함수에 기능을 추가하는 것

class 부모클래스 (): def 같은함수명 (self): print(“something”)

class 자식클래스 ( 부모클래스명 ): def 같은함수명 (self): 부모클래스 . 같은함수명 (self) print(“something new”)

Page 80: Python 정리

클래스 멤버 (1)

class Animal: count_=0 # 클래스 변수 def __init__(self, name): # 인스턴스 변수 self.name=name Animal.increase_count def print_info(self): # 인스턴스 메서드 print(self.name) @classmethod # 클래스 메서드 def increase_count(cls): cls.count_=cls.count_+1 print(cls.count_) @classmethod # 클래스 메서드 def get_object(cls, a, b): return cls(" 동물원형 "+str(a+b)+"마리 ")

#Animal.count 해도 어디서나 사용 가능 클래스 변수

()# 클래스메소드를 참조하니까 Animal.을 사용함

# 이 안에서 연산을 할 수 있으니까 , classmethod 를 사용하는 것

Page 81: Python 정리

클래스 멤버 (2)

class Pet: def play(self): # 인스턴스 메서드 print("play with " + self.name)

class Cat(Animal, Pet): def __init__(self, name, owner): # 인스턴스

변수 Animal.__init__(self, name) # 재정의 self.owner= owner def print_info(self): # 인스턴스 메서드 Animal.print_info(self) # 재정의 print(self.owner) @classmethod # 클래스 메서드 def get_object(cls): return cls(" 고양이원형 ", " 주인원형 ")

Page 82: Python 정리

클래스 멤버 (3)

foo=Animal("곰 ") #Animal 클래스를 이용해서 "곰 " 이란 name인자를 객체를 만듭니다 .

foo.print_info()

nabi=Cat(" 나비 ", "박연우 ")nabi.print_info()nabi.play()

nero=Cat("네로 ", " 김종국 ")nero.print_info()nero.play()

bar =Animal.get_object(1,2)bar.print_info()

kit=Cat.get_object()kit.print_info()

1곰

2나비박연우play with 나비

3네로김종국play with 네로

4동물원형 3마리

5고양이원형주인원형

Page 83: Python 정리

0

countAnimal

increase_count(cls)get_object(cls)

Pet Cat

get_object(cls)

name=“곰”foo

print_info()

name=“네로”owner=“ 김종국”

nero

print_info()

name=“ 고양이원형”owner=“ 주인원형”

kit

print_info()

name=“ 나비”owner=“박연우”

nabi

print_info()

name=“ 동물”bar

print_info()클래스 메서드 사용

Page 84: Python 정리

Object Chainclass Policeman: def __init__(self): print("freeze!") self.use=Weapon() class Weapon: def __init__(self): print("use me!") def a_gun(self): return "bang!" jack=Policeman()print(jack.use.a_gun())

# association 관계에서 사용

#생성자 함수에서 자동 실행

freeze!use me!

bang!

Page 85: Python 정리

7. Exception

Page 86: Python 정리

예외처리

try except : 예외 원인이 자신에게 있을 때

raise : 예외를 발생시킴 , caller 가 예외 처리

Page 87: Python 정리

try except

try: 예외 발생할 가능성이 있는 코드except XxxError as e: 예외 발생하면 실행할 코드else: 예외가 발생하지 않고 , 정상 실행될 때 실행할 코드finally: 항상 실행할 코드

Page 88: Python 정리

try excepttry: print(div(3, 0)) print(" 프로그램 실행됨 ")except ZeroDivisionError as e: print(e)else: print(" 프로그래밍 정상 실행됨 ")finally: print(" 언제나 항상 실행 ") print(div(18, 3))

error 발생error 로 실행 불가

division by zero

try 안쪽 문이 실행되면 , 실행됨

언제나 항상 실행6.0 (try, except,

finally 를 함께 쓰는 것이 좋음 )

Page 89: Python 정리

raise

• 강제로 예외를 발생시킴• 예외 처리는 caller 가 함

Page 90: Python 정리

raiseclass bird: def tweet(self): raise NotImplementedError class Accipitriformes(bird): pass eagle=Accipitriformes()eagle.tweet()

NotImplementedError

Page 91: Python 정리

8. Module

Page 92: Python 정리

import

•import 모듈명 - import copy

•from 모듈명 import 클래스명 - from math import pi

•import 모듈명 as 사용할 이름 - import tensorflow as tf

Page 93: Python 정리

import 모듈명

장점 - 짧게 사용 가능 - 모듈 안의 다른 클래스를 사용할 때 , 새로

import 할 필요 없음단점 - 멤버를 사용할 때마다 , 모듈명을 사용해야

함 ex) sqlite3.connect()

from 모듈명 import 클래스명

장점 - 모듈 안 멤버를 쓸 때 적게 타이핑 할 수 있다 . ex) OperationalError() #sqlite3

안의 메서드인 OperationalError 를 sqlite3. 과 같이 사용할 필요 없음

단점 - 같은 모듈 안의 다른 멤버를 사용하기

위해서는 import 문을 다시 써야 함 - 멤버가 어떤 맥락에서 쓰여지는지 모호해 짐 ex) ceil() 이라고만 하면 , 어떤

의미에서 사용하는지 잘 모르게 됨 . #math.ceil() 하면 명확해 짐

* from 모듈명 import * -> 사용하지 않는 것이 좋음 , 코드가

길어지면 , 모듈의 어떤 멤버를 사용하는지 모르게 됨

Page 94: Python 정리

모듈의 경로

•작업디렉토리 (Current working directory)•PYTHONPATH 환경변수에등록된위치 - export PYTHONPATH=$PYTHONPATH:/home/user/mymodule•표준라이브러리디렉토리 - C:\python35\Lib•sys.path 로현재경로확인 , sys.path.append() 로추가 , remove() 로제거

Page 95: Python 정리

Module 관리if __name__=="__main__": print("execute from inside")else: print("execute from another module") execute from inside

# 모듈 안에 적어서 , 모듈 안에서만 실행되고 , import 되서는 자동으로 실행되지 않도록 함

Page 96: Python 정리

모듈 설치 : PIP

Python 을 환경변수에 추가Cmd 창에 python –m pip install 패키지명자동으로 패키지가 설치됨

Page 97: Python 정리

namespace

Page 98: Python 정리

Namespace

프로젝트

패키지

함수

패키지

변수

모듈

Namespace 관리를 통해 동일한 변수명을 사용할 수 있게 됨

Page 99: Python 정리

Namespace 확인하기

2) 객체 .__docs__ 객체에 속해 있는 변수 , 함수를 딕셔너리로 표시

1) dir() namespace 를 리스트로 표시

Page 100: Python 정리

9. FILE I/O

Page 101: Python 정리

File I/O

변수 =open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

'r' - 읽기 모드'w' - 쓰기 모드'x' open for exclusive creation, failing if the file already exists 'a' - 읽기 모드 , 파일 마지막부터 삽입 시작 'b' - 이진 모드 't' - 텍스트 모드 (디폴트 ) '+' open a disk file for updating (reading and writing) 'U' universal newlines mode (deprecated)

f=open("file.txt", 'w') f.write("something new") f.close()

With 문을 쓰면 close() 없이 가능

with open("file2.txt", 'w') as f: f.write("something cool")

Page 102: Python 정리

try: f=open("data.txt", "rt", encoding="utf8") line=f.readline() for i in range(5): print(line.rstrip("\n")) line=f.readline()except Exception as e: print(e) passfinally: f.close()

rstrip() 오른쪽 공백 제거

readline() 은 한 줄 씩

Page 103: Python 정리

try: f=open("data.txt", "rt", encoding="utf8") lines=f.readlines() print("read data Title") print(len(lines)) for i in range(len(lines)): print(lines[i].rstrip("\n"))except Exception as e: print(e) passfinally: f.close()

Page 104: Python 정리

try: f=open("data.txt", "rt", encoding="utf8") lines=f.readlines() print("read data Title") print(len(lines)) for i in range(int(len(lines)/4)): name=lines[4*i+0].rstrip("\n") email=lines[4*i+1].rstrip("\n") phone=lines[4*i+2].rstrip("\n") address=lines[4*i+3].rstrip("\n") cust=Customer(name, email, phone, address) print(cust.to_string())except Exception as e: print(e) passfinally: f.close()

Page 105: Python 정리

10. Case study

Page 106: Python 정리

user_manager

• Coding file

Page 107: Python 정리

customer manager db versionimport sqlite3from sqlite3 import OperationalError

class Customer: def __init__(self, name, phone, email, address): self.name = name self.phone = phone self.email = email self.address = address def to_string(self): str_ = " 이름 : {0}, 전화 : {1}, 이메일 : {2}, 주소 : {3}" return str_.format(self.name, self.phone, self.email,

self.address) def to_csv(self): str_ ="{0},{1},{2},{3}" return str_.format(self.name, self.phone, self.email,

self.address) class VIPCustomer(Customer) : def __init__(self, name, phone, email, address, note): Customer.__init__(self, name, phone, email, address) self.note = note

VIPCCustomer : class Customer를 상속 받는다 .

Customer class

Page 108: Python 정리

customer manager db version def to_string(self): return Customer.to_string(self) + ", 특징 :

{0}".format(self.note) def to_csv(self): str_ = Customer.to_csv(self) + ",{0}" return str_.format(self.note) def print_menu(): print("1. 입력 , 2. 수정 , 3. 삭제 , 4. 리스트 , 5. 조회 , 6. 종

료 ") menu = 0 try: menu = int(input(" 메뉴를 선택하세요 :")) except ValueError: raise Exception(" 메뉴 입력 에러입니다 .") return menu def get_name(): name = input(" 이름 입력하세요 .").strip() return name

Page 109: Python 정리

customer manager db versiondef insert_cust_info(): con = sqlite3.connect("customer.db") cursor = con.cursor() print(" 입력 메뉴를 선택했습니다 .=====================") name = input(" 이름 : ").strip() phone = input(" 전화번호 : ").strip() email = input(" 이메일 : ").strip() address = input(" 주소 : ").strip() is_vip = input("VIP 입니까 ?(Y/N): ").strip() if is_vip.upper() == "Y" : note = input(" 특징 : ").strip() sql_ = "INSERT INTO customer VALUES('{0}', '{1}',

'{2}', '{3}', '{4}')" cursor.execute(sql_.format(name, phone, email,

address, note)) else : sql_ = "INSERT INTO customer VALUES('{0}', '{1}',

'{2}', '{3}', '{4}')" cursor.execute(sql_.format(name, phone, email,

address, "")) con.commit() print("Data Inserted") con.close()

upper 메소드를 사용해서 , y 나 Y를 입력해도 작동함

SQL 문장을 사용

Page 110: Python 정리

customer manager db versiondef get_cust_info(name): con = sqlite3.connect("customer.db") cursor = con.cursor() sql_ = "SELECT * FROM customer WHERE name='{0}'" cursor.execute(sql_.format(name)) cust = None for row in cursor: if len(row[4]) == 0: #note 정보가 없을 경우

Customer cust = Customer(row[0], row[1], row[2],

row[3]) else: cust = VIPCustomer(row[0], row[1], row[2],

row[3], row[4]) con.close() return cust

Page 111: Python 정리

customer manager db versiondef update_cust_info(name_): con =

sqlite3.connect("customer.db") cursor = con.cursor() print(" 수정 메뉴를 선택했습니다 .") cust = get_cust_info(name_) if cust: name = input(" 이름 [" +

cust.name + "]: ").strip() if len(name) == 0: name = cust.name phone = input(" 전화번호 [" +

cust.phone + "]: ").strip() if len(phone) == 0: phone = cust.phone email = input(" 이메일 [" +

cust.email + "]: " ).strip() if len(email) == 0: email = cust.email address = input(" 주소 [" +

cust.address + "]: ").strip() if len(address) == 0: address = cust.address is_vip = input("VIP 입니까 ?

(Y/N): ").strip()

sql_ = "UPDATE customer SET name='{0}', phone='{1}', email='{2}', address='{3}', note='{4}' WHERE name='{5}'"

if is_vip.upper() == "Y" : note = input(" 특징 :

").strip()

cursor.execute(sql_.format(name, phone, email, address, note, name_))

else:

cursor.execute(sql_.format(name, phone, email, address, "", name_))

con.commit() con.close() print("Data Updated") else: print(" 수정할 데이터가

없습니다 .")

Page 112: Python 정리

customer manager db versiondef delete_cust_info(name): print(" 삭제 메뉴를 선택했습니다 .") con = sqlite3.connect("customer.db") cursor = con.cursor() cust = get_cust_info(name) if cust: is_del = input("{0}님의 정보를 삭제하겠습니까 ?Y/N:

".format(name)) if is_del.upper() == "Y" : sql_= "DELETE FROM customer WHERE

name='{0}'" cursor.execute(sql_.format(name)) con.commit() print(" 삭제했습니다 .") else: print(" 삭제를 취소했습니다 .") else: print(" 삭제할 정보가 없습니다 .") con.close()

Page 113: Python 정리

customer manager db versiondef list_cust_info(): print(" 리스트 메뉴를 선택했습니다 .") con = sqlite3.connect("customer.db") cursor = con.cursor() cursor.execute("SELECT * FROM customer") for row in cursor: if len(row[4]) == 0: #note 정보가 없을 경우

Customer cust = Customer(row[0], row[1], row[2],

row[3]) else: cust = VIPCustomer(row[0], row[1], row[2],

row[3], row[4]) print(cust.to_string()) con.close()

Page 114: Python 정리

customer manager db versiondef view_cust_info(name): print("뷰 메뉴를 선택했습니다 .") con = sqlite3.connect("customer.db") cursor = con.cursor() sql_ = "SELECT * FROM customer WHERE name='{0}'" cursor.execute(sql_.format(name)) for row in cursor: if len(row[4]) == 0: #note 정보가 없을 경우

Customer cust = Customer(row[0], row[1], row[2],

row[3]) else: cust = VIPCustomer(row[0], row[1], row[2],

row[3], row[4]) print(cust.to_string()) con.close()

Page 115: Python 정리

customer manager db versiondef main(): try: con

=sqlite3.connect("customer.db")

cursor = con.cursor() cursor.execute("CREATE

TABLE customer(name text, phone text, email text, address text, note text)")

con.commit() except OperationalError as e: pass #print(e) finally: con.close() while 1: menu = print_menu() if menu == 1: insert_cust_info() elif menu == 2:

update_cust_info(get_name()) elif menu == 3:

delete_cust_info(get_name())

elif menu == 4: list_cust_info() elif menu == 5:

view_cust_info(get_name()) elif menu == 6: print(" 프로그램을

종료합니다 .") break else : print(" 없는 메뉴 입니

다 .") if __name__ == "__main__": main()

Page 116: Python 정리

close()