[Python] 참조와 복사

import copya=[1,2,[3,4]]##참조 (c의 포인터와 유사)b=ab[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

[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.pyimport mod1import mod2 as alias_mod    #모듈 별칭 설정from mod3 import modfunc3   #모듈의 특정 함수,클래스 등을 현재 네임스페이스에 등록 (전체는 *)print mod1.modfunc1(2,3)print alias_mod.modfunc2(5,3)print modfunc3(3,3)

[Python] 클래스

class mycls(object):        #() 안의 값은 상속받을 클래스    “mycls is tutorial class” #클래스 문서화 문자열    def __init__(self):        #클래스 초기화 함수        print “class initialize”    def func1(self,txt):    #class의 함수들의 첫번째 파라미터는 객체 자신을 가리키는 값 (통상적으로 self를 사용)        print “func1 : %s” … 더 읽기

[Python] 코루틴

def cor(txt):    print “coroutine start”    while True:        line = (yield)  #send로 전달받은 값을 line에 저장        if txt in line:            print linec=cor(“py”) #코루틴 초기화c.next()    #코루틴 실행c.send(“show me the money”) #코루틴에 값 전달c.send(“snoopy”)c.send(“black sheep wall”)c.send(“python”)c.close()   #코루틴 종료

[Python] 예외처리

def trys(x,y):    try:        x / y        if y == 100:            raise ValueError     #강제로 예외 발생        elif y == 99:            raise NameError     #except에 명시적으로 정의되지 않은 예외 발생    except ZeroDivisionError:   … 더 읽기

[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 ir=1g=gene(6)while r

[Python] 파일 입출력

f=open(“C:\Windows\System32\drivers\etc\hosts”) #파일 객체 생성f2=open(“out.log”,”w”)line=f.readline() #파일 readwhile line:    print line,    # ,는 줄바꿈 생략    #print(line,end=”) #파이썬3    print >>f2,line # f2에 line 내용 출력    #print(line,file=f2)  #파이썬3    line=f.readline()f.close()for line2 in open(“C:\Windows\System32\drivers\etc\hosts_tmp”):    print line2,

[Python] 함수

count=0def func(a,b=1):    #두번째 인수에 기본값 설정    “func() is tutorial function” #함수 문서화 문자열    global count    #전역 변수를 함수 내에서 사용    count += 1    print “call count : %d” % count    print a,”+”,b    return a+bprint func(4,5)print func(9)print func.__doc__
바로가기