본문 바로가기
반응형

프로그래밍 기초/Python15

[Python] 참조와 복사 import copy a=[1,2,[3,4]] ##참조 (c의 포인터와 유사)b=a b[1]=5print a #a도 변경됨print b ##얕은 복사c=list(a) c.append(5)print a #a에는 원소가 추가되지 않음print cc[2][1]=44print a #기존 원소의 객체는 변경됨print c ##깊은 복사d=copy.deepcopy(a) d[2][1]=999print a #변경되지 않음print d 2016. 3. 13.
[Python] 모듈화 ##모듈 1 : mod1.pydef modfunc1(a,b): return a+b ##모듈 2 : mod2.pydef modfunc2(a,b): return a-b ##모듈 3 : mod3.pydef modfunc3(a,b): return a*b ##메인 : main.py import mod1import mod2 as alias_mod #모듈 별칭 설정from mod3 import modfunc3 #모듈의 특정 함수,클래스 등을 현재 네임스페이스에 등록 (전체는 *) print mod1.modfunc1(2,3)print alias_mod.modfunc2(5,3)print modfunc3(3,3) 2016. 3. 13.
[Python] 클래스 class mycls(object): #() 안의 값은 상속받을 클래스 "mycls is tutorial class" #클래스 문서화 문자열 def __init__(self): #클래스 초기화 함수 print "class initialize" def func1(self,txt): #class의 함수들의 첫번째 파라미터는 객체 자신을 가리키는 값 (통상적으로 self를 사용) print "func1 : %s" % txt def func2(self): print "func2" mc=mycls()print mc.__doc__mc.func1("gogo")mc.func2()if isinstance(mc,mycls): #객체 인스턴스의 객체 타입 확인 print "mc is mycls object" del mc #.. 2016. 3. 13.
[Python] 코루틴 def cor(txt): print "coroutine start" while True: line = (yield) #send로 전달받은 값을 line에 저장 if txt in line: print line c=cor("py") #코루틴 초기화 c.next() #코루틴 실행c.send("show me the money") #코루틴에 값 전달c.send("snoopy")c.send("black sheep wall")c.send("python")c.close() #코루틴 종료 2016. 3. 13.
[Python] 예외처리 def trys(x,y): try: x / y if y == 100: raise ValueError #강제로 예외 발생 elif y == 99: raise NameError #except에 명시적으로 정의되지 않은 예외 발생 except ZeroDivisionError: #처리할 예외 타입 지정 print "ZeroDivisionError Occurred" except TypeError as e: #예외 내용을 e에 저장 print "TypeError Occurred : %s" % e except (IndentationError,ValueError): #처리할 예외를 다수 지정 print "IndentationError or ValueError Occurred" except: #기본 예외 처리 print.. 2016. 3. 8.
[Python] 생성기 def gene(n): print "Generator start" while n < 10: yield n #현재 n 값을 반환, 생성기 자체는 종료되지 않고 멈춰있음 n += 1 print "Generator end" for i in gene(1): #순차적으로 생성기 호출 (next) print i r=1g=gene(6) while r 2016. 3. 8.
반응형