파이썬+주요+용어+정리 20160304

  • View
    4.269

  • Download
    1

  • Category

    Software

Preview:

Citation preview

PYTHON 주요이해하기Moon Yong Joon

기본

식별자

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

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

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

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

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

Variable

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

변수 내의 값 수치값 문자열

컨테이너함수

클래스

튜플리스트

딕션너리

집합변수 Variable

객체의 참조 즉 , 주소 저장

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

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

변수 정의 ( 할당 )

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

Assignment & Type infer-ence

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

I = 1l = “string”l = 1.1

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

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

Building Block

Building block Expression Function Object Variable : point to object Command

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']>>>

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

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

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

함수 외부 변수는 전역변수

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)

Namespace

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

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

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

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

프로젝트패키지

패키지모듈

함수클래스

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

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

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

Literal 처리

왜 객체화 했을까 ?

값 객체

수치값문자열튜플

Immutuable( 값객체 )

Mutuable( 참조객체 )

리스트딕션너리

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

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

객체 값 처리하는 예시

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 처럼 처리가 된다 .숫자 객체가 생성되면 어디서나 동일한 참조를 통해 처리한다 .

Object Value Bound/unbound

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

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

DATATYPE

Mutable & immutable

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

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

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)

comprehension

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

Sequenec Types

String/unicode

Buffer/range

List/tuple

참조 container

참조참조

값container

** string 일경우 값만 처리

Elements 관리

Map 타입 -dictionary

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

참조 container

Name 1 값

Name 2

con-tainer

참조

참조

:

:

Dictionary Type

조건제시법 / 원소나열법수학 집합을 표시할 때 원소를 나열하는 법과 특정 조건을 함축하여 표시

# 원소나열 S  = {1, 2, 4, 8, ..., 2¹²}

# 조건 제시 M = {x | x in S and x even}

Comprehension조건 제시 표현은 표현식 for i in sequence if 논리식

표현식 연속처리 연속처리 제약

For 문 : If 문 표현식

동일 표현

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]>>>

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

>>> s = set() >>> for i in range(10) : … s.add(i) >>> s{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

>>> s1 = {x for x in range(9)}>>> s1{0, 1, 2, 3, 4, 5, 6, 7, 8}

Dict Comprehension사전 정의시 값을 정하지 않고 호출 시 사전 내의 값들이 처리되도록 구성 A = { 표현식 for (k,v) in sequence if 논리식 }

>>> d = {}>>> for (k,v) in zip(range(9),range(9)) : … d[k] = v >>> d {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8}

>>> d1 = {x:y for (x,y) in zip(range(9),range(9)) } >>> d1{0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8}>>>

함수

Function 기초

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

함수 객체함수인자객체

함수 명( 참조 )

함수 정의함수정의는 function class 의 인스턴스 객체가 만들어지는 임

object

codefunction함수정의

함수 인스턴스 생성

<type function > 조회함수를 정의해서 기본 조회

def add(x=1,y=1) : """ add x, y """ print(" vars : ",vars()) print(" locals : ", locals()) return x + y add(5,5)

print("func __name__ : ",add.__name__)print("func name : ",add.func_name)print("func __doc__ : ",add.func_doc)print("func_default : ",add.func_defaults)

# 결과값 vars : {'y': 5, 'x': 5} locals : {'y': 5, 'x': 5}func __name__ : addfunc name : addfunc __doc__ : add x, y func_default : (1, 1)

<type code> 내부 조회함수에 정의된 내부 코드에 대한 조회

def add1(x=1,y=1) : """ add1 x, y """ print(" vars : ",vars()) print(" locals : ", locals()) return x + y

print(" add1 code type ")print(add1.func_code.co_name)print(add1.func_code.co_filename)print(add1.func_code.co_argcount)print(add1.func_code.co_code)

# 처리 결과 add1 code type add1C:/myPython/keyword/keyword_test.py2t

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

함수정의함수호출 1

함수호출 2

함수호출 3

함수호출 4

Stack

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

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

globalBuilt-in

함수 Scope

함수 Namespace

local 내부함수local

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

함수 -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())

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

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

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

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

Function Parameter

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

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

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

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

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

함수 인자 – 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

함수정의

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

외부변수를 함수 변수 활용함수의 인자를 함수 외부와 내부에서 활용하려면 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]

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

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

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

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

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

함수 - 가변인자 - 값 (*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) }

함수 - 가변인자 - 키 / 값 (**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} }

Function Call

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

연속 ( 재귀 ) 호출

특정 시점 호출

부분 호출

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

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

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

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 에 새로운 함수 영역이 생겨서 처리한다

함수 – 시점 호출 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>>>

함수 – 시점 호출 :Generator 함수를 호출해도 계속 저장 함수를 호출 처리가 종료되면 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

함수 – 시점호출 : Generator – 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>>>

함수 - 부분호출 : 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) 출력

함수 - 부분 호출 : 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) 출력

Nested Function

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

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

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

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

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

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

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

내외부 함수에 대한 변수 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()

First Class Object

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

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)

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

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

( 참조주소 )

함수 정의변수

변수에 할당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)

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

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

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

# 함수 실행print call_func(greet)

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

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

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

익명함수

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

Lambda 인자 : 표현식

함수 객체함수인자객체

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

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

함수 – 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)

Closure

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

외부함수

내부함수

외부함수이름공간

내부함수이름공간

Closure context 구성

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

함수 – 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__ 는 튜플로 구성되어 자유변수에 대해 객체로 구성됨

함수 – 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}

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

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

외부함수Context

내부함수Context

Local Local

IntFloat string

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

Function Chaining

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

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

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

High Order Function

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]

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

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

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

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

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 된 결과를 리턴하는 함수

Function Decorator

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

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

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

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

함수 2( 함수3)

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

@f1 @f2

Decorator 순서

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

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()

외부함수

전달함수함수 실행

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

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)

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. 전달함수 실행

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")

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. 전달함수 실행

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

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

@decorate1@decorate2@decorate3def func : pass

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. 전달함수 실행

복수 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 함수 정의 함수 실행

CLASS

클래스 변수와 메소드

클래스 변수와 메소드 정의@classmethod 를 메소드 위에 정의하고 메소드 첫번자 인자도 cls 즉 클래스를 받아서 처리

class Account_Nubmer(object) : __Account_No = 0 @classmethod def set_AN(cls) : cls.__Account_No +=1 @classmethod def get_AN(cls) : cls.set_AN() return cls.__Account_No

인스턴스 변수와 메소드

인스턴스 변수와 메소드 정의인스턴스 변수는 __init__ 메소드 내에 self 연산자와 정의 인스턴스 메소는 는 파라미터 첫번째 인자에 self 를 전달

class Transaction(object) : def __init__(self,tr_no,event,account_no,amount): self.tr_no = tr_no #event :debt, credit,issue self.account_no = account_no self.event = event self.amount = amount def get_Transaction(self) : return (self.tr_no, self.event, self.account_no, self-.amount)

Class 기초

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> ... ...

클래스에서 객체 생성하기

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 내의 인스턴스 메소드

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

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 생성

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

User de-finedClass

Instance

Instance

Instance

Built-inClass

상속 인스턴스화

Object Scope

Object Namespace

Class Member

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}

인스턴스 메소드

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.

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} # 인스턴스 객체 관리 영역

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

메소드 접근자

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

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

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

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

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

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

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

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

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

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 생성 및 호출

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

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)

Method & Object Chain

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()

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

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

생성자와 소멸자

생성자 -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)

생성자 정의

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

소멸자 - 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

소멸자 정의

소멸자 활용

Class 구조

클래스 구조 알기 (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

클래스 구조

클래스 구조 알기 (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

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 처리

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 정의

클래스와 인스턴스 접근

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()

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

내장 객체

내장 객체

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()

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

내장 객체

내장 객체

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

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__

Class Inheritance

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

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

Inheritance- scope

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

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 정의 인스턴스 생성 및 호출

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)

인스턴스 생성 및 호출

Overriding

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

연산자 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

Information Hiding

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

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 명칭

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

Information hiding –Descriptor(Property)

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

Class P Instance p1{‘x’: }

Descriptor/Property

x

생성

인스턴스생성

p1.x 접근

Property 내 메소드 호출하여 처리

DESCIPTOR

Descriptor Protocol

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

Descriptor 종류Method descriptor 와 Data descripter 로 구분

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

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

__delete__(self, instance) 구현

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)

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)

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

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 생김 )

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}

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 생김 )

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__

# 처리결과값31152872 <property ob-ject at 0x7fea026d3e10> 31152872 1001 -12 {'_x': -12}

Object

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

모든 것은 객체

값 문자열컨테이너

함수클래스

튜플리스트

딕션너리

집합

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

파일모듈 패키지

모듈

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

>>> 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'>

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

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

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

Association

Association객체간에 관계를 구성하여 처리객체내부에 관계 객체를 생성하여 해당 객체의 기능을 처리

AB

Association:Composite

#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

Association: Composite 예시

# association 클래스 정의class Other(object):

def override(self): print "OTHER override()"

def implicit(self): print "OTHER implicit()"

def altered(self): print "OTHER altered()"

객체관의 관계가 상속이 아닌 사용관계 (use) 로 전환# 사용 클래 스 정의class Child(object):

def __init__(self): # 인스턴스 생성시 속성으로 정이 self.other = Other()

def implicit(self): self.other.implicit()

def override(self): print "CHILD override()"

def altered(self): print "CHILD, BEFORE OTHER al-tered()" self.other.altered() print "CHILD, AFTER OTHER altered()"

Association:Aggregation

#class 정의하고 인스턴스에서 타 객체를 호출class B(object): pass

class A(object): def __init__(self, b): self.b = b

b = B() a = A(b)

__init__ 메소드에 사용 객체를 받아서 내부에서 처리

Dependency객체간에 관계를 구성하여 처리객체내부에 관계 객체로써 메소드 등에서 일회성으로 해당 객체를 생성하여 기능을 처리

AB

Dependency

class C: def __init__(self ): print 'a' self.b = B() def ccc(self, b) : return b.bbb()

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

print a.b.bbb()

print a.ccc(B())

객체의 관계가 일회성 적으로 처리가 되는 관계

객체 . 메소드 (인스턴스객체 ) 처리# 결과값abB instance method NonebB instance method None

Self 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()

객체 내의 메소드의 결과를 자기자신으로 리턴하여 메소드를 연속해 호출하여 처리

타 객체 Method Chain

class A: def __init__(self ): print 'a' self.b = B() class B: def __init__(self ): self.c = C() print 'b' def bbb(self): print "B instance method " return self.c class C: def __init__(self ): print 'c' def ccc(self): print "C instance method "

클래스 정의시 내부에서 인스턴스를 가진 경우 chain 처리를 위해 return 으로 해당 객체를 전달

# 결과값acbB instance method C instance method None

a = A()

print a.b.bbb().ccc()

Duck typing

Duck typeing 정의 방법다양한 클래스가 동일한 메소드를 처리할 수 있도록 인터페이스를 갖도록 만드는 법

함수

클래스

Duck typing 에 필요한 함수 정의 후 인스턴스들의 메소드 호출 처리

Duck typing 에 필요한 클래스 정의 후 인스턴스들의 메소드 호출 처리

Duck typeing : 함수 구현 (1)Duck typeing 함수 정의 후 클래스에 동일한 메소드 정의

def in_the_forest(duck): duck.quack() duck.feathers()

class Duck: def quack(self): print("Quaaaaaack!") def feathers(self): print("The duck has white and gray feathers.")

class Person: def quack(self): print("The person imitates a duck.") def feathers(self): print("The person takes a feather from the ground and shows it.") def name(self): print("John Smith")

함수 정의 클래스 정의

Duck typeing : 함수 구현 (2)Duck typeing 처리

def game(): donald = Duck() john = Person() in_the_forest(donald) in_the_forest(john)

print "function duck typeing "game()

# 실행 결과function duck typeing Quaaaaaack!The duck has white and gray feathers.The person imitates a duck.The person takes a feather from the ground and shows it.

Duck typeing : 클래스 구현 (1)

Duck typeing 클래스 정의 후 클래스에 동일한 메소드 정의

class InTheForest() : @staticmethod def quack(self) : self.quack() @staticmethod def feathers(self) : self.feathers() @classmethod def all(cls,self) : cls.quack(self) cls.feathers(self)

class Duck: def quack(self): print("Quaaaaaack!") def feathers(self): print("The duck has white and gray feathers.")

class Person: def quack(self): print("The person imitates a duck.") def feathers(self): print("The person takes a feather from the ground and shows it.") def name(self): print("John Smith")

함수 정의 클래스 정의

Duck typeing : 클래스 구현 (2)

Duck typeing 처리

def gameC(): donald = Duck() john = Person() InTheForest.all(donald) InTheForest.all(john)

print " class duck typeing "gameC()

# 실행 결과 class duck typeing Quaaaaaack!The duck has white and gray feathers.The person imitates a duck.The person takes a feather from the ground and shows it.

Recommended