SlideShare a Scribd company logo
1 of 349
PYTHON
이해하기
Moon Yong Joon
DATA(OBJECT) TYPE
Data(Object) Type 기본
Values and data types:원자
파이썬은 실제 리터럴 즉 값이 객체이므로 기본
객체의 구성을 이해해야
>>> type(1.1)
<class ‘float'>
>>>
>>> type(17)
<class 'int'>
값을 type() 함수를 이용해 데이터 타
입을 확인
reference
type
value
float
주소
1.1
reference
type
value
int
주소
17
데이터 관리 방안(예시)
Values and data types:분자
프로그램 언어에서 가장 기본적인 것인 Value가
가진 형식이 데이터 타입
reference
type
element
reference
type
value
int
주소
1
reference
type
element
list
주소
reference
type
value
reference
type
value
…
주소
list
>>> v = [1,2,[3,4]]
>>> v
[1, 2, [3, 4]]
>>>
Data types 이해하기
int 등 data type의 키워드는 클래스 객체이고
type 클래스 객체를 구현해서 처리
>>> int.__class__.__name__
'type'
>>> intobj =1
>>> intobj.__class__.__name__
'int'
>>> isinstance(intobj.__class__, type)
True
>>> intobj2 = int(1)
>>> intobj2
1
>>> intobj2.__class__.__name__
'int'
>>> type.__class__.__name__
'type'
>>>
생성된 int 타입이 type 클
래스 객체를 상속여부 확인
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'>
1
1
<type 'float'>
1.1
1.1
<type 'list'>
[1, 2]
[1, 2]
타입 특성
데이터를 관리하는 기준이며 파이썬은 최상위 타입
을 Object로 선정해서 모든 것을 object instance로
처리
>>> type(object)
<type 'type'>
>>> type(1)
<type 'int'>
>>> isinstance(1,object)
True
>>>
Object를 최상위 클래스 객체이며 이
를 상속받아 구현
숫자 1도 실제 자연수라는 클래스객
체에서 생성된 객체라서 Object이 인
스턴스 객체
Builtin type 특성
객체 내부에 정해진 값이 변경이 가능한지를 구분
=> 컨테이너 타입 중에 실제 값이 정해지지 않은
경우 요소들을 변경이 가능
 변경불가(immutable) : int, float, complex,
str/unicode bytes, tuple, frozenset
 변경가능(mutable) : list, dict, set, bytes-array
Mutable & immutable
Mutable & immutable
Values 내부의 값을 변경이 가능한지 점검하여 값을 변
경.
특히 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)
Type Conversion
Type conversion
변수에서 참조하는 타입을 자신의 필요한 타입으로 변경이 필요할 경우 사용
파이썬에 제공되는 함수들을 이용해서 사용하면 됨
>>> v = 1
>>> str(v)
'1'
>>> float(str(v))
1.0
>>> int(str(v))
1
>>> x = int()
>>> x
0
>>> y = str()
>>> y
''
>>> z = float()
>>> z
0.0
>>>
타입 함수를 이용해서 변수에 할
당하면 초기값을 세팅
타입 함수를 이용해서 변수에 적
절한 타입으로 변환
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'>
>>>
String에서 integer 변환
문자열은 문자와 숫자로 구성될 수 있으므로 숫
자여부를 확인하고 형변환을 해야 함
>>> # string을 내부를 숫자로
>>> v = '1‘
>>> #string 내장 메소드로 숫자여부 체크
>>> if v.isdigit() :
... s = int(v)
... else :
... s = 0
...
>>> s
1
Numeric Type
숫자타입
숫자에 대한 객체를 관리하는 데이터 타입
Numberic Types
int
float
long
complex
>>> id(1)
5939944
>>> v = 1
>>> type(v)
<type 'int'>
>>> id(v)
5939944
>>>
숫자타입도 하나의 객체이므로 1 이 생성
되면 동일한 context 내에서는 동일한 객체
id를 가지고 사용
숫자타입 - 기본처리
숫자 타입에 기본으로 처리 되는 함수, operator
Operation Result Notes
x + y sum of x and y
x - y difference of x and y
x * y product of x and y
x / y quotient of x and y
x // y (floored) quotient of x and y
x % y remainder of x / y
-x x negated
+x x unchanged
abs(x) absolute value or magnitude of x
int(x) x converted to integer
long(x) x converted to long integer
float(x) x converted to floating point
complex(re,im)
a complex number with real part re, imaginary part im. im defaults to z
ero.
c.conjugate() conjugate of the complex number c
divmod(x, y) the pair (x // y, x % y)
pow(x, y) x to the power y
x ** y x to the power y
Sequence Type
Sequence 타입
다양한 객체의 값을 원소로 값는 데이터 타입
Sequenec Types
String/unicode
Buffer/range
List/tuple
참조 container
참조
참조
값
container
** string 일경우 값만
처리
Elements 관리
Sequence 타입- 기본처리
Sequence 타입에 기본으로 처리 되는 함수,
operator
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 0
s[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 s
min(s) smallest item of s
max(s) largest item of s
Sequence-Accessing Values
Sequence 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
>>>
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] = 100
Traceback (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
support item assignment
List type Tuple type String type
Sequence- 내장함수 이용하기
Sequence 내장함수를 이용한 sorted, reversed,
enumerate, zip을 처리
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print i, v
...
0 tic
1 tac
2 toe
>>> l1 = [1,2,3,4]
>>> la = ['a','b','c','d']
>>> for k,v in zip(l1,la) :
... print k, v
...
1 a
2 b
3 c
4 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()
Sequence : Slice
Sequence slicing
Sequence 타입(string, list, tuple)에 대한 내부 원소들
을 추출하기 위해 slicing을 사용
[ 시작위치:종료위치:간격]
>>> mystring[0:5] 'hello' >>> mystring[6:-1] 'worl'
Sequence slicing-역방향
문자열을 역으로 처리하기
>>> s = 'hello'
>>> s[-3:]
'llo'
>>> s[:-3]
'he'
>>> s[-1:-3]
''
>>> s[-1:0]
''
>>> s[-1:-3:-1]
'ol'
>>>
역방향으로 처리하기 위해서는
변수명[시작점:종료점:스텝] 정의
시 역방향으로 정의하고 스템도
마이너스로 표시하면 역으로 처
리
Sequence : String Type
Sequence-Updating String
String에 대한 update는 기본적으로 새로운
String Instance 만드는 것
>>> s
'string'
>>> id(s)
6122176
>>> v = "updating " + s
>>> id(v)
106043176
>>> v
'updating string'
>>>
>>> s
'string'
>>>
String-operator
Operator Description Example
+ Concatenation - Adds values on either side of the operator a + b will give HelloPython
* Repetition - Creates new strings, concatenating multiple co
pies 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 t
he given string
M not in a will give 1
r/R Raw String - Suppresses actual meaning of Escape characte
rs. The syntax for raw strings is exactly the same as for nor
mal strings with the exception of the raw string operator, t
he letter "r," which precedes the quotation marks. The "r" ca
n be lowercase (r) or uppercase (R) and must be placed imm
ediately preceding the first quote mark.
print r'n' prints n and print R'n'prints 
n
% Format - Performs String formatting See at next section
Sequence-String 메소드(1)
String 내장 메소드
Method Description
capitalize() Capitalizes first letter of string
center(width, fillchar) Returns a space-padded string with the original string centered to a total
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.
Sequence-String 메소드(2)
String 내장 메소드
Method Description
find(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(st
ring))
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
alphanumeric and false otherwise.
isalpha() Returns true if string has at least 1 character and all characters are
alphabetic 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.
Sequence-String 메소드(3)
String 내장 메소드
Method Description
isspace() 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
sequence 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.
Sequence-String 메소드(4)
String 내장 메소드
Method Description
max(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
occurrences if max given.
rfind(str, beg=0,end=len(stri
ng))
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.cou
nt(str))
Splits string according to delimiter str (space if not provided) and returns
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.
Sequence-String 메소드(5)
String 내장 메소드
Method Description
startswith(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
uppercase and the rest are lowercase.
translate(table, deletechars
="")
Translates string according to translation table str(256 chars), removing
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
characters; 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.
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
 문자 ""
' 단일 인용부호(')
" 이중 인용부호(")
Sequence : List Type
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
Sequence-List 용 내장함수
내장함수중에 리스트 타입을 처리
Function Description
cmp(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.
Sequence-List class 구조 확인
list는 하나의 class object로 제공
>>> list
<type 'list'>
>>> id(list)
505560280
>>>
>>>
>>> l1 = list()
>>> id(l1)
106593376
>>> isinstance(l1,list)
True
>>>
list의 인스턴스를 생성하고
isinstance 함수를 이용하여
인스턴스 여부 확인
Sequence-List 메소드
리스트 내장 메소드
Method Description
list.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
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]
>>>
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]
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]
>>>
Sequence : Tuple Type
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
Sequence- Tuple 용 내장함수
내장함수 중에 tuple 타입을 처리
Function Description
cmp(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.
Set Type
Set 타입
중복을 허용하지 않고, 순서가 없음 (unordered)
교집합(&), 합집합(|), 차집합(-) 연산 처리
Set: mutable set
Frozenset: immutable set
Set 타입 – 생성시 주의
Set()으로 생성시 파라미터는 1개만 받는다. 리스트
등 mutable 객체를 요소로 처리할 수 없다.
그래서 튜플로 처리
>>> 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)))
>>> s
set([1, 2])
>>>
>>> s = set({'a':1})
>>> s
set(['a'])
Set은 구조상 내부 요소
가 변경이 가능한 값으
로 구성할 수 없다
Set에 dictionary로 생
성시 요소는 변경할 수
없는 immutable타입만
생성함
Set 타입 – Set 생성 및 추가
Set type은 mutable 타입이므로 생성 후 원소를
추가나 삭제가 가능
>>>
>>> s = set([1,2,3])
>>> s
set([1, 2, 3])
>>> s1 = set([1,2,3,3,4,4])
>>> s1
set([1, 2, 3, 4])
>>> s.add(5)
>>> s
set([1, 2, 3, 5])
>>> s1.add(5)
>>> s1
set([1, 2, 3, 4, 5])
>>>
Set 타입 – FrozenSet 생성 및 추가
FrozenSet type은 immutable 타입이므로 생성
후 원소를 추가나 삭제가 불가능
>>> s = frozenset([1,2,3])
>>> s
frozenset([1, 2, 3])
>>> s.add(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute
'add'
>>>
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 b
oth
s.copy() new set with a shallow copy of s
Set 타입- set 확장처리
Operation Equivalent Result
s.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 bot
h 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 eithe
r 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; rais
es KeyError if empty
s.clear() remove all elements from set s
Map Type
Map 타입-dictionary
Key/Value로 원소를 관리하는 데이터 타입
요소들은 변경가능하므로 변수에 복사시
참조 container
Name 1 값
Name 2
contain
er
참조
참조
:
:
Dictionary Type
Map 타입 - Accessing Elements
Key/Value로 원소를 관리하므로 Key를 가지고
원소를 검색
>>> dd = {'name': 'dahl', 'age':50}
>>> dd
{'age': 50, 'name': 'dahl'}
>>> dd['name']
'dahl'
>>>
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에 할당: 기존
에 있는 값을 변경
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
>>> dd
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'dd' is not defined
>>>
기존 원소 하나 삭제
Dict 삭제
모든 원소 삭제
Map 타입 – dict 지원 내장함수
Dictionary 타입에 원소 하나만 삭제, 원소들을
삭제, dictionary instance 삭제
Function Description
cmp(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.
Map 타입 -dict class 구조 확인
dict는 하나의 class object로 제공
>>> dict
<type 'dict'>
>>> id(dict)
505532280
>>>
>>> d1 = dict()
>>> id(d1)
105140272
>>> isinstance(d1,dict)
True
>>>
Dict의 인스턴스를 생성하고
isinstance 함수를 이용하여
인스턴스 여부 확인
Map 타입 -dictionary 메소드
내장 메소드
Method Description
dict.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,
default=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
Boolean type & None
Boolean 타입
파이썬은 true/false를 실제 값이 존재하거나 없
는 경우에 조건식을 확정할 경우 사용
값 참 or 거짓
"python" 참
"" 거짓
[1, 2, 3] 참
[] 거짓
() 거짓
{} 거짓
1 참
0 거짓
None 거짓
If 조건식 :
pass
Else :
pass
조건식에 값들이 참과
거짓을 구별하여 처리
None
정의된 것이 없는 타입을 세팅할 때 표시
 존재하지 않음(Not Exists)
 정의되지 않음(Not Assigned, Not Defined)
 값이 없음(No Value)
 초기값(Initialized Value)
STRING FORMAT
String Format –메소드(권장)
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
>>>
{} 개수가 파라미터보다 작
으면 처리가 되지만 {] 개수
가 파라미터 개수보다 많으
면 오류가 발생
String-format함수 – name 치환
 “ {파라미터 변수명 } “.format(변수명=값,)
>>> "{first} {second} ".format(first=1, second=2)
'1 2 '
>>>
{} 개수가 파라미터보다 작
으면 처리가 되지만 {] 개수
가 파라미터 개수보다 많으
면 오류가 발생
String-format함수 – 혼용 치환
 “ {위치} {파라미터 변수명 } “.format(값, 변수
명=값)
>>> "{0} {second} ".format(1, second=2)
'1 2 '
>>>
파라미터 처리시
Key/Value 처리는 맨 뒷에
서 처리가 되어야 함
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!!!!!!!!'
공백을 채우려면 정렬
방법부호 앞에 공백으
로 대체할 문자를 표
시하면 된다.
String Format -%
String-format처리(%)
문자열 내에 특정 값들을 재정의하는 방법
“스트링 “ % (스트링 내부 매칭 값)
text = "%d little pigs come out or I'll %s and %s and %s" % (3, 'huff', 'puff', 'blow down')
String-format 코드
문자열 내에 특정 값들을 재정의하는 방법
“스트링 “ % (스트링 내부 매칭 값)
코드 설명
%s 문자열 (String)
%c 문자 한개(character)
%d 정수 (Integer)
%f 부동소수 (floating-point)
%o 8진수
%x 16진수
%% Literal % (문자 % 자체)
String-format 정렬 방식
 %(부호)숫자(.숫자)?[s|d|f]
 + 부호는 우측정렬/ -부호는 좌측 정렬
>>> v = 10
>>> " a %10d a " % v
' a 10 a '
>>> " a %-10d a " % v
' a 10 a '
>>>
OPERATOR
내장 메소드와 연산자
파이썬은 연산자에 상응하는 내장메소드를 가지
고 있어 각 타입별로 연산자에 상응한 내장메소
드가 구현되어 있음
>>> 1+1
2
>>> p=1
>>> p.__add__(1)
2
>>>
>>> "Hello" + "World"
'HelloWorld'
>>> "Hello".__add__("World")
'HelloWorld'
>>>
int 타입이나 str 타입 일 경우
+ 연산자와 __add__() 메소드
는 동일하게 처리됨
사칙연산자
Operator Description Example
+
Addition
Adds values on either side of the operator. a + b = 30
-
Subtraction
Subtracts right hand operand from left hand opera
nd.
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 a
nd returns remainder
b % a = 0
**
Exponent
Performs exponential (power) calculation on opera
tors
a**b =10 to the power 20
// Floor Division - The division of operands where th
e result is the quotient in which the digits after th
e decimal point are removed.
9//2 = 4 and 9.0//2.0 = 4.0
비교연산자
Operator Description Example
== If the values of two operands are equal, then the co
ndition becomes true.
(a == b) is not true.
!= If values of two operands are not equal, then condi
tion becomes true.
<> If values of two operands are not equal, then condi
tion 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 condition beco
mes true.
(a >= b) is not true.
<= If the value of left operand is less than or equal to t
he value of right operand, then condition becomes
true.
(a <= b) is true.
할당연산자
Operator Description Example
= Assigns values from right side operands to left si
de operand
c = a + b assigns value of a
+ b into c
+=
Add AND
It adds right operand to the left operand and assi
gn the result to left operand
c += a is equivalent to c = c
+ a
-=
Subtract AND
It subtracts right operand from the left operand a
nd assign the result to left operand
c -= a is equivalent to c = c
- a
*=
Multiply AND
It multiplies right operand with the left operand a
nd 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 t
he result to left operand
c %= a is equivalent to c = c
% a
**=
Exponent AND
Performs exponential (power) calculation on oper
ators and assign value to the left operand
c **= a is equivalent to c = c
** a
//=
Floor Division
It performs floor division on operators and assign
value to the left operand
c //= a is equivalent to c = c
// a
비트연산자
Operator Description Example
&
Binary AND
Operator copies a bit to the result if it exists
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 bu
t not both.
(a ^ b) = 49 (means 0011 0001)
~
Binary Ones Com
plement
It is unary and has the effect of 'flipping' bit
s.
(~a ) = -61 (means 1100 0011 in 2's
complement form due to a signed bi
nary number.
<<
Binary Left Shift
The left operands value is moved left by the
number of bits specified by the right operan
d.
a << = 240 (means 1111 0000)
>>
Binary Right Shif
t
The left operands value is moved right by th
e number of bits specified by the right oper
and.
a >> = 15 (means 0000 1111)
논리연산자
Operator Description Example
and
Logical AND
If both the operands are true then con
dition becomes true.
(a and b) is true.
or
Logical OR
If any of the two operands are non-ze
ro 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.
논리연산자 - 단축연산
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
>>>
논리 연산 중에 단축연산이 필요한 경우에 사용
하고 두 조건을 전체를 비교할 경우는 기본 논리
연산자를 사용해야 함
논리연산자 – 단축연산 예시
&, | 연산을 비교시 축약형 처리하는데 결과를 리턴함
& : 좌측이 참이면 우측을 리턴
| : 좌측이 거짓이면 우측을 리턴
>>> (10+1) & 0
0
>>> (10+1) | 0
11
>>> 0 |10
10
>>>
멤버쉽 연산자
Operator Description Example
in Evaluates to true if it finds a variable in the spe
cified 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 variable i
n the specified sequence and false otherwise.
x not in y, here not in results in a 1
if x is not a member of sequence y.
식별 연산자
Operator Description Example
is Evaluates to true if the variables on either s
ide of the operator point to the same objec
t and false otherwise.
x is y, here is results in 1 if id(x) equal
s id(y).
is not Evaluates to false if the variables on either
side of the operator point to the same obje
ct and true otherwise.
x is not y, here is not results in 1 if id(
x) is not
연산자 우선순위
Operator Description
** Exponentiation (raise to the power)
~ + - Ccomplement, unary plus and minus (method names for the last two are +@ an
d -@)
* / % // 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 operators
in not in Membership operators
not or and Logical operators
PYTHON
파싱 처리 기준
식별자
식별자 란
식별자는 이름공간에서 별도로 구별할 수 있는 이
름 정의
식별자 대상: 변수, 함수,객체,모듈, 패키지 등등
파이썬은 이름으로 식별하기 때문에 동일한 이름이
만들어지면 재할당됨
식별자 처리 원칙
 클래스 이름은 대문자로 시작
 클래스 이름 이외는 소문자로 시작
 하나의 밑줄과 식별자를 시작하면 Private
 두 개의 주요 밑줄 식별자를 시작하면 강력한
Private
 앞뒤로 두개의 밑줄로 끝나는 경우, 언어 정의
특별한 이름으로 사용
문장 구분
 멀티라인() : 여러 문장을 하나로 처리
 블록 구분 : intention으로 구분
 라인 구분 : 개행문자(n)를 기준으로 구분
 주석 (#) : 파이썬 문장과 구분한 설명
 Doc 설명 : single ('), double (") and triple ('''
or """) quotes 를 프로그램 맨 앞에 넣으면 모듈
명.__doc__ 로 검색가능
 한문장으로 그룹화(;) : 여러문장을 ;로 연결해서
한 문장으로 만들 수 있음
문장 구분- doc 처리
모듈 내부에 모듈에 대한 설명이 필요할 경우 넣는
법
>>> import doctest
hello world
>>> doctest.__doc__
'nCreated on Fri Jan 08 14:46:31
2016nn@author: 06411n'
>>>
# doctest.py
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 08 14:46:31 2016
@author: 06411
"""
print("hello world ")
모듈 처리모듈 작성
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 inference
파이썬 언어는 동적 타입을 체크하므로 주어진 타입을
추정해서 처리
I = 1
l = “string”
l = 1.1
l은 변수이지만 변수 정의와 변수
할당이 동시에 된다.
변수에 할당시 타입을 추정해서
동적으로 정해진다.
파이썬에서 연속적으로 할당시
변수에 저장된 타입이 변경된다.
Variable 삭제
Context 내에서 변수 삭제.
del 변수명, del(변수명) 으로 삭제
>>> a= 1
>>> b =1
>>> a
1
>>> b
1
>>> del a
>>> del(b)
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined
>>>
Building Block
Building block
 Expression
 Function
 Object
 Variable : point to object
 Command
Expression
An expression is a combination of values, variables, and
operators.
표현식을 선언해도 실제 정의되는 것이 객체이므로 별도의 블록이 유지
됨
>>> (i for i in l)
<generator object <genexpr> at 0x06521E68>
>>> dir((i for i in l))
['__class__', '__delattr__', '__doc__', '__format__',
'__getattribute__', '__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
>>> i
1
>>>I = I + 1
Traceback (most recent call last):
File "<stdin>", line 1, in
<module>
NameError: name 'i' is not defined
어휘분석에 따른 할당 될 경우 I + 1 부터 처리시 Unbinding 에러가
발생함 (NameError: name 'i' is not defined)
Namespace
Namespace
파이썬은 모듈, 패키지, 프로젝트 등의 단위로
작업공간을 두고 name을 기준으로 식별한다.
모듈, 패키지, 프로젝트 단위로 동일한 name을
가진 변수, 클래스 객체, 함수, 값 객체 등을 관리
해서 이중으로 발생하지 않도록 처리
Namespace 관리 기준
Import로 패키지를 포함한 모듈을 호출하여 모듈처리 시 식별이 명확하도록 작업공간을 분리
프로젝트는 pythonpath를 기준으로 관리해서 로드한다.
공통 기능은 별도의 모듈로 분리해서 프로젝트를 분리해서 사용해야 이름공간이 충돌을 방지
할 수 있다
모든 객체이므로 이름공간관리
프로젝트
패키지
패키지
모듈
함수
클래스
Namespace 확인하기
Dir() 함수 : 패키지, 모듈 등 네임스페이스 관리를
List로 표시
__dict__ : 객체 네임스페이스를 관리 사전으로 표
시
>>>dir()
>>>dir(패키지)
>>>객체이름.__dict__
>>>
Object Namespace 흐름
Base
class
class
instance instance instance
상속
인스턴스 생성
Dict{}
Dict{}
Dict{} Dict{} Dict{}
Namespace
검색
객체는 자신들이 관리
하는 Namespace 공간
을 생성하며
객체 내의 속성이나 메
소드 호출시 이를 검색
해서 처리
function Namespace 흐름
Namespace
검색
함수는 내부의 로직 처
리를 위한 Namespace
를 별도로 관리한다.
내부함수가 실행되면
외부함수 Namespace
를 참조하여 처리할 수
있다.
하위에서 상위는 참조
가 가능하나 상위에서
하위는 참조가 불가
함수 내부에서
locals()/globals() 관
리 영역 참조가능
모듈
외부함수
내부함수 내부함수 내부함수
영역 참조
영역참조
Dict{}
Dict{}
Dict{} Dict{} Dict{}
Built-in Dict{}
영역 참조
Namespace 기준
 프로젝트
 패키지
 모듈
 함수
 클래스/인스턴스 객체
- 클래스 객체는 클래스 멤버들에 대한 관리할 경우에만 이름
공간 역할을 수행
Control flow
Statement
Statement Description
if statements 조건식 결과가 true 일 경우만 처리
if...else statements 조건식 결과가 true 일 경우는 if 내의 블럭처
리하고 false 일 경우 else 내의 블록 처리
nested if statements If와 elif 조건식 결과가 true 일 경우 블럭처리
하고 모든 조건식이 false 일 경우 else 블럭처
리
For Statement
파이썬에서는 for in (sequence 타입)으로 처리함
For 문을 처리하고 추가적으로 처리할 것이 필요하면
else 구문을 이용하여 처리함
Loop Statement
Loop Type Description
while loop 조건식이 true 일 경우에 실행
for loop sequence 타입에 대해 순환하여 처리
nested loops 순환내에 내부적인 순환조건을 만들 경우 외부
순환에 맞춰 내부 순환이 반복하여 실행
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문을 사용하
지 않아도 처리가 끝나면
클로즈가 자동으로 됨
Break Statement
기존 control flow를 강제로 빠져나갈 경우 필요
for x in range(0, 5):
print(x)
if(x == 6):
break
else:
print("else")
Continue Statement
기존 control flow를 처리시 조건이 맞을 경우 처
음으로 돌아가서 계속 실행할 수 있도록 처리
>>> for i in [1,2,3,4,5] :
... if i == 2 :
... continue
... print i
...
1
3
4
5
Pass Statement
처리가 필요없는 블록이 필요할 경우 pass문을 사용
하여 처리하지 않음
Continue 문장과의 차이점은 pass문은 현재 실행이
없다는 것을 의미만 함
>>> for i in [1,2,3,4,5] :
... if i == 2 :
... pass
... print i
...
1
2
3
4
5
else Statement
For/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
Module/package
모듈
모듈이란 함수나 변수들, 또는 클래스들을 모아놓은 파일
파이썬이 모듈은 하나의 객체이면서 하나의 이름공간을 구성해서 내부 속
성에 대한 처리 방안을 제시한다.
모듈 내의 속성에 대한 접근은 점(.) 연산자를 통해 접근
# 모듈 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.apple()
print mod.tangerine"
모듈 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 ’)
모듈 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 ’)
if __name__ == "__main__":
Command 창에서 모듈을 호출할 경우 __name__ 속성에 “__main__”
으로 들어감
Command 창에서 실행하면 현재 호출된 모듈을 기준으로 실행환경이
설정되기 때문에 “__main__” 이 실행환경이 기준이 됨
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 시 실행되는 영역
모듈 –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
패키지
패키지(Packages)는 도트('.')를 이용하여 파이썬 모듈을 계층적(디렉토리 구조)으로 관리
절대경로
import game.sound.echo # 패키지.패키지.모듈
from game.sound import echo
from game.sound.echo import echo_test # 패키지.패키지.모듈 한 후 모듈속성 정의
상대경로
import .echo # 현재 패키지에 모듈을 import
import ..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
패키지 예시 (1)
1. Kakao 프로젝트는 pythonpath에 등록
2. account 패키지 생성
3. account 패키지 내에 account.py 생성
패키지 예시 (2)
1. myproject 프로젝트는 pythonpath에 등록
2. add_test.py 생성
3. account.account를 import 하여
모듈 :pythonpath 등록
모듈에 대한 검색에서 오류가 발생할 경우 pythonpath에 현재 디렉토
리 위치를 추가해야 함
set PYTHONPATH=c:python20lib;
모듈 : ide에서 path 등록
실제 다양한 패키지를 사용할 경우 각 패키지를 등록해야 한다.
#path
>>> import sys
>>> sys.path
['', 'C:WindowsSYSTEM32python34.zip', 'c:Python34DLLs', 'c:Python34lib', 'c:
Python34', 'c:Python34libsite-packages']
# 현재 작성된 모듈의 위치 등록
>>> sys.path.append("C:/Python/Mymodules")
>>> sys.path
['', 'C:WindowsSYSTEM32python34.zip', 'c:Python34DLLs', 'c:Python34lib',
'c:Python34', 'c:Python34libsite-packages', 'C:/Python/Mymodules']
>>>
>>> import mod2
>>> print(mod2.sum(3,4)) # 결과값 7
FUNCTION
Function 기초
함수
함수 정의와 함수 실행으로 구분
함수를 실행(호출)하기 전에 모듈 내에 함수 정의를
해야 함
#함수 정의
def 함수명(인자) 구문블럭(:)
함수 내부 로직
#함수 실행
함수명(인자)
함수
객체
함수
인자
객체
함수
명
(참조)
함수 내부 구조 알아보기
함수가 정의되면 함수 코드도 하나의 객체로 만들어짐
간단히 함수에 대한 로컬변수 확인해 봄
>>> def add(x,y) :
... return x+y
...
>>> #함수정의에 대한 내부 구조
>>> add.func_code.co_varnames
('x', 'y')
>>>
>>> # 함수코드는 bytecode로 나타남
>>> add.func_code.co_code
'|x00x00|x01x00x17S'
>>>
함수 – 메모리 생성 규칙
 함수 호출 시 마다 Stack에 함수 영역을 구성하
고 실행됨
 함수를 재귀호출할 경우 각 호출된 함수 별로
stack영역을 구성하고 처리
함수정의
함수호출 1
함수호출 2
함수호출 3
함수호출 4
Stack
제일 마지막 호출된 것을 처리가 끝
나면 그 전 호출한 함수를 처리load
함수 – 메모리 생성 예시
정의된 함수에서 실제 함수를 실행시 함수 인스턴스
를 만들어서 실행됨
funcs = []
for i in range(4):
def f():
print I
# 함수 인스턴스를 추가
funcs.append(f)
print funcs
i =0
for 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 1
None
46309104 2
None
46309296 3
None
46363504 4
None
함수 생성된
개수만큼
생성됨
레퍼런스를 정수로
변환처리
함수 변수 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, "): ",result)
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
>>>
함수 – 시점 호출 :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
함수 – 시점호출 : 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
>>>
함수- 부분호출 : 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 partial
def 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 = add
print 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>
10
10
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()
익명함수
함수 - Lambda
Lambda는 단순 처리를 위한 익명함수이고 return을 표시하지 않는다.
익명함수를 정의하고 실행하지만 리턴 결과는 한 개만 전달 할 수 있다.
Lambda 인자 : 표현식
함수
객체
함수
인자
객체
함수명
미존재
(참조주소)
익명함수 정의
변수
필요시 변수에
할당
함수 – Lambda 예시
Lambda는 표현식시 2개의 리턴 값이 생기므로 에러가 발생함
표현식에서 2개 이상 결과를 나타내려면 tuple 처리해야 함
>>> x = lambda x,y : y,x
Traceback (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_contents
print 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)
자유변수가
immutable 일 경
우 내부함수에 생
기지만 변경할 수
없으므로 에러처
리
Locals()함수를 이
용하여 함수에서
관리하는 변수를
출력
outer {'n': 4}
inner {'x': 5, 'n': 4}
함수 – Closure : 자유변수(2)
변수는 Mutable 값과 Immutable 값이 binding되면서 정의되므로
내부함수에서 외부함수의 변수(immutable)에 재할당 시
unboundlocalerror 발생시 해결 방안
 내부함수에 키워드 nonlocal를 변수에 사용
 외부함수에 mutable 값을 할당한 변수를 사용(리스트, 사전으로 정의)
외부함수
Context
내부함수
Context
Local Local
Int
Float
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 6
reduce 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_return
def 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_func
def 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_f
def add_1(x,y):
return x+y
데코레이터 함수 정의 전달 함수 및 데코레이션 정의 함수 할당 및 실행
#데코레이터 호출
x = add_1(5,5)
print(' decorator ', x)
#함수 처리 순서
v = outer_f(add)
v(5,5)
Functools Module
functools.wraps(wrapped[, assigned][,
updated]) 을 이용하여 데코레이션 처리
from functools import wraps
def my_decorator(f):
@wraps(f)
def wrapper(*args, **kwds):
print 'Calling decorated function'
return f(*args, **kwds)
return wrapper
@my_decorator
def 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 Module
functools.wraps(wrapped[, assigned][,
updated]) 을 이용하여 데코레이션 처리
from functools import wraps
def my_decorator(f):
@wraps(f)
def wrapper(*args, **kwds):
print 'Calling decorated function'
return f(*args, **kwds)
return wrapper
@my_decorator
def 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
@decorate3
def func :
pass
Functools Module: 파라미터
데코레이터 파라미터를 처리하기 위해 파라미터
처리하는 함수를 하나 더 처리
from functools import wraps
def 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 함수 1
def 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
@f2
def 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
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__',
'__getattribute__', '__getnewargs__', '__hash__',
'__hex__', '__index__', '__init__', '__int__', '__invert__',
'__long__', '__lshift__', '__mod__', '__mul__', '__neg__',
'__new__', '__nonzero__', '__oct__', '__or__', '__pos__',
'__pow__', '__radd__', '__rand__', '__rdiv__',
'__rdivmod__', '__reduce__', '__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',
'denominator', '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 & instance
Class Object는 인스턴스를 만드는 기준을 정리한다.
클래스를 정의한다고 하나의 저장공간(Namespace) 기준이 되는 것은 아니다.
- 클래스 저장공간과 인스턴스 저장공간이 분리된다
User
defined
Class
Instance
Instance
Instance
Built-in
Class
상속 인스턴스화
Object Scope
Object Namespace
Class Member
Class Member
Class 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 Attributes
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 Member
Instance 생성시 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.empCount
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 관계)가 있을 경
우 메소드 결과값을 객체로 받아 연속적으로 실행하도록 처리
객체.내부객체.메소
드 처리
#결과값
a
b
B 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 = pt1
pt3 = pt1
print id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts
del pt1
del pt2
del 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 namespace
Class 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(변수) Access
Class/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(메소드) Access
Class 정의시 인스턴스 메소드 정의를 하면 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',
'__module__': '__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 Access
Instance의 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
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130
파이썬정리 20160130

More Related Content

What's hot

파이썬+객체지향+이해하기 20160131
파이썬+객체지향+이해하기 20160131파이썬+객체지향+이해하기 20160131
파이썬+객체지향+이해하기 20160131
Yong Joon Moon
 
파이썬 반복자 생성자 이해하기
파이썬 반복자 생성자 이해하기파이썬 반복자 생성자 이해하기
파이썬 반복자 생성자 이해하기
Yong Joon Moon
 

What's hot (20)

파이썬+Json+이해하기 20160301
파이썬+Json+이해하기 20160301파이썬+Json+이해하기 20160301
파이썬+Json+이해하기 20160301
 
Python array.array 모듈 이해하기
Python array.array 모듈 이해하기Python array.array 모듈 이해하기
Python array.array 모듈 이해하기
 
파이썬 심화
파이썬 심화파이썬 심화
파이썬 심화
 
파이썬 플라스크 이해하기
파이썬 플라스크 이해하기 파이썬 플라스크 이해하기
파이썬 플라스크 이해하기
 
파이썬 함수 이해하기
파이썬 함수 이해하기 파이썬 함수 이해하기
파이썬 함수 이해하기
 
Python+numpy pandas 4편
Python+numpy pandas 4편Python+numpy pandas 4편
Python+numpy pandas 4편
 
파이썬 Xml 이해하기
파이썬 Xml 이해하기파이썬 Xml 이해하기
파이썬 Xml 이해하기
 
파이썬+데이터+구조+이해하기 20160311
파이썬+데이터+구조+이해하기 20160311파이썬+데이터+구조+이해하기 20160311
파이썬+데이터+구조+이해하기 20160311
 
파이썬 문자열 이해하기
파이썬 문자열 이해하기파이썬 문자열 이해하기
파이썬 문자열 이해하기
 
파이썬+함수이해하기 20160229
파이썬+함수이해하기 20160229파이썬+함수이해하기 20160229
파이썬+함수이해하기 20160229
 
파이썬 namespace Binding 이해하기
파이썬 namespace Binding 이해하기 파이썬 namespace Binding 이해하기
파이썬 namespace Binding 이해하기
 
파이썬+객체지향+이해하기 20160131
파이썬+객체지향+이해하기 20160131파이썬+객체지향+이해하기 20160131
파이썬+객체지향+이해하기 20160131
 
Processing 기초 이해하기_20160713
Processing 기초 이해하기_20160713Processing 기초 이해하기_20160713
Processing 기초 이해하기_20160713
 
파이썬+Operator+이해하기 20160409
파이썬+Operator+이해하기 20160409파이썬+Operator+이해하기 20160409
파이썬+Operator+이해하기 20160409
 
파이썬 Special method 이해하기
파이썬 Special method 이해하기파이썬 Special method 이해하기
파이썬 Special method 이해하기
 
파이썬 반복자 생성자 이해하기
파이썬 반복자 생성자 이해하기파이썬 반복자 생성자 이해하기
파이썬 반복자 생성자 이해하기
 
Python+numpy pandas 1편
Python+numpy pandas 1편Python+numpy pandas 1편
Python+numpy pandas 1편
 
파이썬 Collections 모듈 이해하기
파이썬 Collections 모듈 이해하기파이썬 Collections 모듈 이해하기
파이썬 Collections 모듈 이해하기
 
엘라스틱서치 이해하기 20160612
엘라스틱서치 이해하기 20160612엘라스틱서치 이해하기 20160612
엘라스틱서치 이해하기 20160612
 
파이썬 파일처리 이해하기
파이썬 파일처리 이해하기파이썬 파일처리 이해하기
파이썬 파일처리 이해하기
 

Viewers also liked

파이썬 문자열 이해하기
파이썬 문자열 이해하기파이썬 문자열 이해하기
파이썬 문자열 이해하기
Yong Joon Moon
 
『고성능 파이썬』 - 맛보기
『고성능 파이썬』 - 맛보기『고성능 파이썬』 - 맛보기
『고성능 파이썬』 - 맛보기
복연 이
 
파이썬+정규표현식+이해하기 20160301
파이썬+정규표현식+이해하기 20160301파이썬+정규표현식+이해하기 20160301
파이썬+정규표현식+이해하기 20160301
Yong Joon Moon
 

Viewers also liked (20)

파이썬 문자열 이해하기
파이썬 문자열 이해하기파이썬 문자열 이해하기
파이썬 문자열 이해하기
 
『고성능 파이썬』 - 맛보기
『고성능 파이썬』 - 맛보기『고성능 파이썬』 - 맛보기
『고성능 파이썬』 - 맛보기
 
파이썬+클래스+구조+이해하기 20160310
파이썬+클래스+구조+이해하기 20160310파이썬+클래스+구조+이해하기 20160310
파이썬+클래스+구조+이해하기 20160310
 
도커의 기초 - 김상필 솔루션즈 아키텍트 :: AWS Container Day
도커의 기초 - 김상필 솔루션즈 아키텍트 :: AWS Container Day도커의 기초 - 김상필 솔루션즈 아키텍트 :: AWS Container Day
도커의 기초 - 김상필 솔루션즈 아키텍트 :: AWS Container Day
 
파이썬+네트워크 20160210
파이썬+네트워크 20160210파이썬+네트워크 20160210
파이썬+네트워크 20160210
 
파이썬 Datetime 이해하기
파이썬 Datetime 이해하기파이썬 Datetime 이해하기
파이썬 Datetime 이해하기
 
Django로 배우는 쉽고 빠른 웹개발 study 자료
Django로 배우는 쉽고 빠른 웹개발 study 자료Django로 배우는 쉽고 빠른 웹개발 study 자료
Django로 배우는 쉽고 빠른 웹개발 study 자료
 
파이썬 객체 클래스 이해하기
파이썬  객체 클래스 이해하기파이썬  객체 클래스 이해하기
파이썬 객체 클래스 이해하기
 
파이썬+정규표현식+이해하기 20160301
파이썬+정규표현식+이해하기 20160301파이썬+정규표현식+이해하기 20160301
파이썬+정규표현식+이해하기 20160301
 
파이썬 class 및 인스턴스 생성 이해하기
파이썬 class 및 인스턴스 생성 이해하기파이썬 class 및 인스턴스 생성 이해하기
파이썬 class 및 인스턴스 생성 이해하기
 
파이썬 sqlite 이해하기
파이썬 sqlite 이해하기파이썬 sqlite 이해하기
파이썬 sqlite 이해하기
 
파이썬 유니코드 이해하기
파이썬 유니코드 이해하기파이썬 유니코드 이해하기
파이썬 유니코드 이해하기
 
python data model 이해하기
python data model 이해하기python data model 이해하기
python data model 이해하기
 
확률 통계 (파이썬)
확률 통계 (파이썬)확률 통계 (파이썬)
확률 통계 (파이썬)
 
파이썬 데이터 검색
파이썬 데이터 검색파이썬 데이터 검색
파이썬 데이터 검색
 
도커 컨테이너 활용 사례 Codigm - 남 유석 개발팀장 :: AWS Container Day
도커 컨테이너 활용 사례 Codigm - 남 유석 개발팀장 :: AWS Container Day도커 컨테이너 활용 사례 Codigm - 남 유석 개발팀장 :: AWS Container Day
도커 컨테이너 활용 사례 Codigm - 남 유석 개발팀장 :: AWS Container Day
 
클라우드 뉴노멀 시대의 글로벌 혁신 기업들의 디지털 트랜스포메이션 :: 정우진 이사
클라우드 뉴노멀 시대의 글로벌 혁신 기업들의 디지털 트랜스포메이션 :: 정우진 이사클라우드 뉴노멀 시대의 글로벌 혁신 기업들의 디지털 트랜스포메이션 :: 정우진 이사
클라우드 뉴노멀 시대의 글로벌 혁신 기업들의 디지털 트랜스포메이션 :: 정우진 이사
 
파이썬 Numpy 선형대수 이해하기
파이썬 Numpy 선형대수 이해하기파이썬 Numpy 선형대수 이해하기
파이썬 Numpy 선형대수 이해하기
 
게임 디렉팅 튜토리얼
게임 디렉팅 튜토리얼게임 디렉팅 튜토리얼
게임 디렉팅 튜토리얼
 
Docker로 서버 개발 편하게 하기
Docker로 서버 개발 편하게 하기Docker로 서버 개발 편하게 하기
Docker로 서버 개발 편하게 하기
 

Similar to 파이썬정리 20160130

Data Mining with R CH1 요약
Data Mining with R CH1 요약Data Mining with R CH1 요약
Data Mining with R CH1 요약
Sung Yub Kim
 
빠르게 활용하는 파이썬3 스터디(ch1~4)
빠르게 활용하는 파이썬3 스터디(ch1~4)빠르게 활용하는 파이썬3 스터디(ch1~4)
빠르게 활용하는 파이썬3 스터디(ch1~4)
SeongHyun Ahn
 
Smalltalk at Altlang 2008
Smalltalk at Altlang 2008Smalltalk at Altlang 2008
Smalltalk at Altlang 2008
daliot
 

Similar to 파이썬정리 20160130 (20)

강의자료3
강의자료3강의자료3
강의자료3
 
Start IoT with JavaScript - 4.객체1
Start IoT with JavaScript - 4.객체1Start IoT with JavaScript - 4.객체1
Start IoT with JavaScript - 4.객체1
 
2015 Kitel C 언어 강좌3
2015 Kitel C 언어 강좌32015 Kitel C 언어 강좌3
2015 Kitel C 언어 강좌3
 
Python3 brief summary
Python3 brief summaryPython3 brief summary
Python3 brief summary
 
Python Programming: Type and Object
Python Programming: Type and ObjectPython Programming: Type and Object
Python Programming: Type and Object
 
파이썬 기본 문법
파이썬 기본 문법파이썬 기본 문법
파이썬 기본 문법
 
R 프로그래밍 기본 문법
R 프로그래밍 기본 문법R 프로그래밍 기본 문법
R 프로그래밍 기본 문법
 
3주차 스터디
3주차 스터디3주차 스터디
3주차 스터디
 
Startup JavaScript 4 - 객체
Startup JavaScript 4 - 객체Startup JavaScript 4 - 객체
Startup JavaScript 4 - 객체
 
Data Mining with R CH1 요약
Data Mining with R CH1 요약Data Mining with R CH1 요약
Data Mining with R CH1 요약
 
R 기초 : R Basics
R 기초 : R BasicsR 기초 : R Basics
R 기초 : R Basics
 
빠르게 활용하는 파이썬3 스터디(ch1~4)
빠르게 활용하는 파이썬3 스터디(ch1~4)빠르게 활용하는 파이썬3 스터디(ch1~4)
빠르게 활용하는 파이썬3 스터디(ch1~4)
 
스칼라와 스파크 영혼의 듀오
스칼라와 스파크 영혼의 듀오스칼라와 스파크 영혼의 듀오
스칼라와 스파크 영혼의 듀오
 
Java stream v0.1
Java stream v0.1Java stream v0.1
Java stream v0.1
 
Java stream v0.1
Java stream v0.1Java stream v0.1
Java stream v0.1
 
C review
C  reviewC  review
C review
 
Smalltalk at Altlang 2008
Smalltalk at Altlang 2008Smalltalk at Altlang 2008
Smalltalk at Altlang 2008
 
Apply교육
Apply교육Apply교육
Apply교육
 
Java mentoring of samsung scsc 0
Java mentoring of samsung scsc   0Java mentoring of samsung scsc   0
Java mentoring of samsung scsc 0
 
Java advancd ed10
Java advancd ed10Java advancd ed10
Java advancd ed10
 

More from Yong Joon Moon

파이썬 프로퍼티 디스크립터 이해하기
파이썬 프로퍼티 디스크립터 이해하기파이썬 프로퍼티 디스크립터 이해하기
파이썬 프로퍼티 디스크립터 이해하기
Yong Joon Moon
 
파이썬 내부 데이터 검색 방법
파이썬 내부 데이터 검색 방법파이썬 내부 데이터 검색 방법
파이썬 내부 데이터 검색 방법
Yong Joon Moon
 

More from Yong Joon Moon (20)

rust ownership
rust ownership rust ownership
rust ownership
 
Scala namespace scope
Scala namespace scopeScala namespace scope
Scala namespace scope
 
Scala companion object
Scala companion objectScala companion object
Scala companion object
 
Scala block expression
Scala block expressionScala block expression
Scala block expression
 
Scala self type inheritance
Scala self type inheritanceScala self type inheritance
Scala self type inheritance
 
Scala variable
Scala variableScala variable
Scala variable
 
Scala type class pattern
Scala type class patternScala type class pattern
Scala type class pattern
 
Scala match pattern
Scala match patternScala match pattern
Scala match pattern
 
Scala implicit
Scala implicitScala implicit
Scala implicit
 
Scala type args
Scala type argsScala type args
Scala type args
 
Scala trait usage
Scala trait usageScala trait usage
Scala trait usage
 
Scala nested function generic function
Scala nested function generic functionScala nested function generic function
Scala nested function generic function
 
Scala dir processing
Scala dir processingScala dir processing
Scala dir processing
 
Scala syntax function
Scala syntax functionScala syntax function
Scala syntax function
 
스칼라 클래스 이해하기 _Scala class understanding
스칼라 클래스 이해하기 _Scala class understanding스칼라 클래스 이해하기 _Scala class understanding
스칼라 클래스 이해하기 _Scala class understanding
 
파이썬 프로퍼티 디스크립터 이해하기
파이썬 프로퍼티 디스크립터 이해하기파이썬 프로퍼티 디스크립터 이해하기
파이썬 프로퍼티 디스크립터 이해하기
 
파이썬 내부 데이터 검색 방법
파이썬 내부 데이터 검색 방법파이썬 내부 데이터 검색 방법
파이썬 내부 데이터 검색 방법
 
파이썬 class 및 function namespace 이해하기
파이썬 class 및 function namespace 이해하기파이썬 class 및 function namespace 이해하기
파이썬 class 및 function namespace 이해하기
 
파이썬 엑셀_csv 처리하기
파이썬 엑셀_csv 처리하기파이썬 엑셀_csv 처리하기
파이썬 엑셀_csv 처리하기
 
Python+numpy pandas 3편
Python+numpy pandas 3편Python+numpy pandas 3편
Python+numpy pandas 3편
 

파이썬정리 20160130

  • 4. Values and data types:원자 파이썬은 실제 리터럴 즉 값이 객체이므로 기본 객체의 구성을 이해해야 >>> type(1.1) <class ‘float'> >>> >>> type(17) <class 'int'> 값을 type() 함수를 이용해 데이터 타 입을 확인 reference type value float 주소 1.1 reference type value int 주소 17 데이터 관리 방안(예시)
  • 5. Values and data types:분자 프로그램 언어에서 가장 기본적인 것인 Value가 가진 형식이 데이터 타입 reference type element reference type value int 주소 1 reference type element list 주소 reference type value reference type value … 주소 list >>> v = [1,2,[3,4]] >>> v [1, 2, [3, 4]] >>>
  • 6. Data types 이해하기 int 등 data type의 키워드는 클래스 객체이고 type 클래스 객체를 구현해서 처리 >>> int.__class__.__name__ 'type' >>> intobj =1 >>> intobj.__class__.__name__ 'int' >>> isinstance(intobj.__class__, type) True >>> intobj2 = int(1) >>> intobj2 1 >>> intobj2.__class__.__name__ 'int' >>> type.__class__.__name__ 'type' >>> 생성된 int 타입이 type 클 래스 객체를 상속여부 확인
  • 7. 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'> 1 1 <type 'float'> 1.1 1.1 <type 'list'> [1, 2] [1, 2]
  • 8. 타입 특성 데이터를 관리하는 기준이며 파이썬은 최상위 타입 을 Object로 선정해서 모든 것을 object instance로 처리 >>> type(object) <type 'type'> >>> type(1) <type 'int'> >>> isinstance(1,object) True >>> Object를 최상위 클래스 객체이며 이 를 상속받아 구현 숫자 1도 실제 자연수라는 클래스객 체에서 생성된 객체라서 Object이 인 스턴스 객체
  • 9. Builtin type 특성 객체 내부에 정해진 값이 변경이 가능한지를 구분 => 컨테이너 타입 중에 실제 값이 정해지지 않은 경우 요소들을 변경이 가능  변경불가(immutable) : int, float, complex, str/unicode bytes, tuple, frozenset  변경가능(mutable) : list, dict, set, bytes-array
  • 11. Mutable & immutable Values 내부의 값을 변경이 가능한지 점검하여 값을 변 경. 특히 variables, 함수 파라미터에 복사할 경우 실제 값 객 체가 변경가능여부에 따라 다른 경우가 발생함 Mutable은 주로 리스트, 딕셔너리 타입으로 내부 값인 요소에 추가하는 것이므로 변수나 함수 파라미터로 사용 해도 변경( swallow copy 사용) Mutable 처리할 경우 처음이 값이 변경되지 않으려면 참 조만 복사하지 말고 전체 값을 복사해야 별도의 참조가 생겨 다른 값 객체로 인식함(deepcopy 이용)
  • 12. 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)
  • 14. Type conversion 변수에서 참조하는 타입을 자신의 필요한 타입으로 변경이 필요할 경우 사용 파이썬에 제공되는 함수들을 이용해서 사용하면 됨 >>> v = 1 >>> str(v) '1' >>> float(str(v)) 1.0 >>> int(str(v)) 1 >>> x = int() >>> x 0 >>> y = str() >>> y '' >>> z = float() >>> z 0.0 >>> 타입 함수를 이용해서 변수에 할 당하면 초기값을 세팅 타입 함수를 이용해서 변수에 적 절한 타입으로 변환
  • 15. 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'> >>>
  • 16. String에서 integer 변환 문자열은 문자와 숫자로 구성될 수 있으므로 숫 자여부를 확인하고 형변환을 해야 함 >>> # string을 내부를 숫자로 >>> v = '1‘ >>> #string 내장 메소드로 숫자여부 체크 >>> if v.isdigit() : ... s = int(v) ... else : ... s = 0 ... >>> s 1
  • 18. 숫자타입 숫자에 대한 객체를 관리하는 데이터 타입 Numberic Types int float long complex >>> id(1) 5939944 >>> v = 1 >>> type(v) <type 'int'> >>> id(v) 5939944 >>> 숫자타입도 하나의 객체이므로 1 이 생성 되면 동일한 context 내에서는 동일한 객체 id를 가지고 사용
  • 19. 숫자타입 - 기본처리 숫자 타입에 기본으로 처리 되는 함수, operator Operation Result Notes x + y sum of x and y x - y difference of x and y x * y product of x and y x / y quotient of x and y x // y (floored) quotient of x and y x % y remainder of x / y -x x negated +x x unchanged abs(x) absolute value or magnitude of x int(x) x converted to integer long(x) x converted to long integer float(x) x converted to floating point complex(re,im) a complex number with real part re, imaginary part im. im defaults to z ero. c.conjugate() conjugate of the complex number c divmod(x, y) the pair (x // y, x % y) pow(x, y) x to the power y x ** y x to the power y
  • 21. Sequence 타입 다양한 객체의 값을 원소로 값는 데이터 타입 Sequenec Types String/unicode Buffer/range List/tuple 참조 container 참조 참조 값 container ** string 일경우 값만 처리 Elements 관리
  • 22. Sequence 타입- 기본처리 Sequence 타입에 기본으로 처리 되는 함수, operator 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 0 s[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 s min(s) smallest item of s max(s) largest item of s
  • 23. Sequence-Accessing Values Sequence 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 >>>
  • 24. 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] = 100 Traceback (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 support item assignment List type Tuple type String type
  • 25. Sequence- 내장함수 이용하기 Sequence 내장함수를 이용한 sorted, reversed, enumerate, zip을 처리 >>> for i, v in enumerate(['tic', 'tac', 'toe']): ... print i, v ... 0 tic 1 tac 2 toe >>> l1 = [1,2,3,4] >>> la = ['a','b','c','d'] >>> for k,v in zip(l1,la) : ... print k, v ... 1 a 2 b 3 c 4 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()
  • 27. Sequence slicing Sequence 타입(string, list, tuple)에 대한 내부 원소들 을 추출하기 위해 slicing을 사용 [ 시작위치:종료위치:간격] >>> mystring[0:5] 'hello' >>> mystring[6:-1] 'worl'
  • 28. Sequence slicing-역방향 문자열을 역으로 처리하기 >>> s = 'hello' >>> s[-3:] 'llo' >>> s[:-3] 'he' >>> s[-1:-3] '' >>> s[-1:0] '' >>> s[-1:-3:-1] 'ol' >>> 역방향으로 처리하기 위해서는 변수명[시작점:종료점:스텝] 정의 시 역방향으로 정의하고 스템도 마이너스로 표시하면 역으로 처 리
  • 30. Sequence-Updating String String에 대한 update는 기본적으로 새로운 String Instance 만드는 것 >>> s 'string' >>> id(s) 6122176 >>> v = "updating " + s >>> id(v) 106043176 >>> v 'updating string' >>> >>> s 'string' >>>
  • 31. String-operator Operator Description Example + Concatenation - Adds values on either side of the operator a + b will give HelloPython * Repetition - Creates new strings, concatenating multiple co pies 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 t he given string M not in a will give 1 r/R Raw String - Suppresses actual meaning of Escape characte rs. The syntax for raw strings is exactly the same as for nor mal strings with the exception of the raw string operator, t he letter "r," which precedes the quotation marks. The "r" ca n be lowercase (r) or uppercase (R) and must be placed imm ediately preceding the first quote mark. print r'n' prints n and print R'n'prints n % Format - Performs String formatting See at next section
  • 32. Sequence-String 메소드(1) String 내장 메소드 Method Description capitalize() Capitalizes first letter of string center(width, fillchar) Returns a space-padded string with the original string centered to a total 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.
  • 33. Sequence-String 메소드(2) String 내장 메소드 Method Description find(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(st ring)) 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 alphanumeric and false otherwise. isalpha() Returns true if string has at least 1 character and all characters are alphabetic 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.
  • 34. Sequence-String 메소드(3) String 내장 메소드 Method Description isspace() 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 sequence 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.
  • 35. Sequence-String 메소드(4) String 내장 메소드 Method Description max(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 occurrences if max given. rfind(str, beg=0,end=len(stri ng)) 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.cou nt(str)) Splits string according to delimiter str (space if not provided) and returns 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.
  • 36. Sequence-String 메소드(5) String 내장 메소드 Method Description startswith(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 uppercase and the rest are lowercase. translate(table, deletechars ="") Translates string according to translation table str(256 chars), removing 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 characters; 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.
  • 37. 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 문자 "" ' 단일 인용부호(') " 이중 인용부호(")
  • 39. 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
  • 40. Sequence-List 용 내장함수 내장함수중에 리스트 타입을 처리 Function Description cmp(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.
  • 41. Sequence-List class 구조 확인 list는 하나의 class object로 제공 >>> list <type 'list'> >>> id(list) 505560280 >>> >>> >>> l1 = list() >>> id(l1) 106593376 >>> isinstance(l1,list) True >>> list의 인스턴스를 생성하고 isinstance 함수를 이용하여 인스턴스 여부 확인
  • 42. Sequence-List 메소드 리스트 내장 메소드 Method Description list.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
  • 43. 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] >>>
  • 44. 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]
  • 45. 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] >>>
  • 47. 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
  • 48. Sequence- Tuple 용 내장함수 내장함수 중에 tuple 타입을 처리 Function Description cmp(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.
  • 50. Set 타입 중복을 허용하지 않고, 순서가 없음 (unordered) 교집합(&), 합집합(|), 차집합(-) 연산 처리 Set: mutable set Frozenset: immutable set
  • 51. Set 타입 – 생성시 주의 Set()으로 생성시 파라미터는 1개만 받는다. 리스트 등 mutable 객체를 요소로 처리할 수 없다. 그래서 튜플로 처리 >>> 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))) >>> s set([1, 2]) >>> >>> s = set({'a':1}) >>> s set(['a']) Set은 구조상 내부 요소 가 변경이 가능한 값으 로 구성할 수 없다 Set에 dictionary로 생 성시 요소는 변경할 수 없는 immutable타입만 생성함
  • 52. Set 타입 – Set 생성 및 추가 Set type은 mutable 타입이므로 생성 후 원소를 추가나 삭제가 가능 >>> >>> s = set([1,2,3]) >>> s set([1, 2, 3]) >>> s1 = set([1,2,3,3,4,4]) >>> s1 set([1, 2, 3, 4]) >>> s.add(5) >>> s set([1, 2, 3, 5]) >>> s1.add(5) >>> s1 set([1, 2, 3, 4, 5]) >>>
  • 53. Set 타입 – FrozenSet 생성 및 추가 FrozenSet type은 immutable 타입이므로 생성 후 원소를 추가나 삭제가 불가능 >>> s = frozenset([1,2,3]) >>> s frozenset([1, 2, 3]) >>> s.add(4) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'frozenset' object has no attribute 'add' >>>
  • 54. 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 b oth s.copy() new set with a shallow copy of s
  • 55. Set 타입- set 확장처리 Operation Equivalent Result s.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 bot h 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 eithe r 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; rais es KeyError if empty s.clear() remove all elements from set s
  • 57. Map 타입-dictionary Key/Value로 원소를 관리하는 데이터 타입 요소들은 변경가능하므로 변수에 복사시 참조 container Name 1 값 Name 2 contain er 참조 참조 : : Dictionary Type
  • 58. Map 타입 - Accessing Elements Key/Value로 원소를 관리하므로 Key를 가지고 원소를 검색 >>> dd = {'name': 'dahl', 'age':50} >>> dd {'age': 50, 'name': 'dahl'} >>> dd['name'] 'dahl' >>>
  • 59. 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에 할당: 기존 에 있는 값을 변경
  • 60. 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 >>> dd Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'dd' is not defined >>> 기존 원소 하나 삭제 Dict 삭제 모든 원소 삭제
  • 61. Map 타입 – dict 지원 내장함수 Dictionary 타입에 원소 하나만 삭제, 원소들을 삭제, dictionary instance 삭제 Function Description cmp(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.
  • 62. Map 타입 -dict class 구조 확인 dict는 하나의 class object로 제공 >>> dict <type 'dict'> >>> id(dict) 505532280 >>> >>> d1 = dict() >>> id(d1) 105140272 >>> isinstance(d1,dict) True >>> Dict의 인스턴스를 생성하고 isinstance 함수를 이용하여 인스턴스 여부 확인
  • 63. Map 타입 -dictionary 메소드 내장 메소드 Method Description dict.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, default=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
  • 65. Boolean 타입 파이썬은 true/false를 실제 값이 존재하거나 없 는 경우에 조건식을 확정할 경우 사용 값 참 or 거짓 "python" 참 "" 거짓 [1, 2, 3] 참 [] 거짓 () 거짓 {} 거짓 1 참 0 거짓 None 거짓 If 조건식 : pass Else : pass 조건식에 값들이 참과 거짓을 구별하여 처리
  • 66. None 정의된 것이 없는 타입을 세팅할 때 표시  존재하지 않음(Not Exists)  정의되지 않음(Not Assigned, Not Defined)  값이 없음(No Value)  초기값(Initialized Value)
  • 69. 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 >>> {} 개수가 파라미터보다 작 으면 처리가 되지만 {] 개수 가 파라미터 개수보다 많으 면 오류가 발생
  • 70. String-format함수 – name 치환  “ {파라미터 변수명 } “.format(변수명=값,) >>> "{first} {second} ".format(first=1, second=2) '1 2 ' >>> {} 개수가 파라미터보다 작 으면 처리가 되지만 {] 개수 가 파라미터 개수보다 많으 면 오류가 발생
  • 71. String-format함수 – 혼용 치환  “ {위치} {파라미터 변수명 } “.format(값, 변수 명=값) >>> "{0} {second} ".format(1, second=2) '1 2 ' >>> 파라미터 처리시 Key/Value 처리는 맨 뒷에 서 처리가 되어야 함
  • 72. 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!!!!!!!!' 공백을 채우려면 정렬 방법부호 앞에 공백으 로 대체할 문자를 표 시하면 된다.
  • 74. String-format처리(%) 문자열 내에 특정 값들을 재정의하는 방법 “스트링 “ % (스트링 내부 매칭 값) text = "%d little pigs come out or I'll %s and %s and %s" % (3, 'huff', 'puff', 'blow down')
  • 75. String-format 코드 문자열 내에 특정 값들을 재정의하는 방법 “스트링 “ % (스트링 내부 매칭 값) 코드 설명 %s 문자열 (String) %c 문자 한개(character) %d 정수 (Integer) %f 부동소수 (floating-point) %o 8진수 %x 16진수 %% Literal % (문자 % 자체)
  • 76. String-format 정렬 방식  %(부호)숫자(.숫자)?[s|d|f]  + 부호는 우측정렬/ -부호는 좌측 정렬 >>> v = 10 >>> " a %10d a " % v ' a 10 a ' >>> " a %-10d a " % v ' a 10 a ' >>>
  • 78. 내장 메소드와 연산자 파이썬은 연산자에 상응하는 내장메소드를 가지 고 있어 각 타입별로 연산자에 상응한 내장메소 드가 구현되어 있음 >>> 1+1 2 >>> p=1 >>> p.__add__(1) 2 >>> >>> "Hello" + "World" 'HelloWorld' >>> "Hello".__add__("World") 'HelloWorld' >>> int 타입이나 str 타입 일 경우 + 연산자와 __add__() 메소드 는 동일하게 처리됨
  • 79. 사칙연산자 Operator Description Example + Addition Adds values on either side of the operator. a + b = 30 - Subtraction Subtracts right hand operand from left hand opera nd. 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 a nd returns remainder b % a = 0 ** Exponent Performs exponential (power) calculation on opera tors a**b =10 to the power 20 // Floor Division - The division of operands where th e result is the quotient in which the digits after th e decimal point are removed. 9//2 = 4 and 9.0//2.0 = 4.0
  • 80. 비교연산자 Operator Description Example == If the values of two operands are equal, then the co ndition becomes true. (a == b) is not true. != If values of two operands are not equal, then condi tion becomes true. <> If values of two operands are not equal, then condi tion 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 condition beco mes true. (a >= b) is not true. <= If the value of left operand is less than or equal to t he value of right operand, then condition becomes true. (a <= b) is true.
  • 81. 할당연산자 Operator Description Example = Assigns values from right side operands to left si de operand c = a + b assigns value of a + b into c += Add AND It adds right operand to the left operand and assi gn the result to left operand c += a is equivalent to c = c + a -= Subtract AND It subtracts right operand from the left operand a nd assign the result to left operand c -= a is equivalent to c = c - a *= Multiply AND It multiplies right operand with the left operand a nd 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 t he result to left operand c %= a is equivalent to c = c % a **= Exponent AND Performs exponential (power) calculation on oper ators and assign value to the left operand c **= a is equivalent to c = c ** a //= Floor Division It performs floor division on operators and assign value to the left operand c //= a is equivalent to c = c // a
  • 82. 비트연산자 Operator Description Example & Binary AND Operator copies a bit to the result if it exists 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 bu t not both. (a ^ b) = 49 (means 0011 0001) ~ Binary Ones Com plement It is unary and has the effect of 'flipping' bit s. (~a ) = -61 (means 1100 0011 in 2's complement form due to a signed bi nary number. << Binary Left Shift The left operands value is moved left by the number of bits specified by the right operan d. a << = 240 (means 1111 0000) >> Binary Right Shif t The left operands value is moved right by th e number of bits specified by the right oper and. a >> = 15 (means 0000 1111)
  • 83. 논리연산자 Operator Description Example and Logical AND If both the operands are true then con dition becomes true. (a and b) is true. or Logical OR If any of the two operands are non-ze ro 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.
  • 84. 논리연산자 - 단축연산 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 >>> 논리 연산 중에 단축연산이 필요한 경우에 사용 하고 두 조건을 전체를 비교할 경우는 기본 논리 연산자를 사용해야 함
  • 85. 논리연산자 – 단축연산 예시 &, | 연산을 비교시 축약형 처리하는데 결과를 리턴함 & : 좌측이 참이면 우측을 리턴 | : 좌측이 거짓이면 우측을 리턴 >>> (10+1) & 0 0 >>> (10+1) | 0 11 >>> 0 |10 10 >>>
  • 86. 멤버쉽 연산자 Operator Description Example in Evaluates to true if it finds a variable in the spe cified 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 variable i n the specified sequence and false otherwise. x not in y, here not in results in a 1 if x is not a member of sequence y.
  • 87. 식별 연산자 Operator Description Example is Evaluates to true if the variables on either s ide of the operator point to the same objec t and false otherwise. x is y, here is results in 1 if id(x) equal s id(y). is not Evaluates to false if the variables on either side of the operator point to the same obje ct and true otherwise. x is not y, here is not results in 1 if id( x) is not
  • 88. 연산자 우선순위 Operator Description ** Exponentiation (raise to the power) ~ + - Ccomplement, unary plus and minus (method names for the last two are +@ an d -@) * / % // 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 operators in not in Membership operators not or and Logical operators
  • 91. 식별자 란 식별자는 이름공간에서 별도로 구별할 수 있는 이 름 정의 식별자 대상: 변수, 함수,객체,모듈, 패키지 등등 파이썬은 이름으로 식별하기 때문에 동일한 이름이 만들어지면 재할당됨
  • 92. 식별자 처리 원칙  클래스 이름은 대문자로 시작  클래스 이름 이외는 소문자로 시작  하나의 밑줄과 식별자를 시작하면 Private  두 개의 주요 밑줄 식별자를 시작하면 강력한 Private  앞뒤로 두개의 밑줄로 끝나는 경우, 언어 정의 특별한 이름으로 사용
  • 93. 문장 구분  멀티라인() : 여러 문장을 하나로 처리  블록 구분 : intention으로 구분  라인 구분 : 개행문자(n)를 기준으로 구분  주석 (#) : 파이썬 문장과 구분한 설명  Doc 설명 : single ('), double (") and triple (''' or """) quotes 를 프로그램 맨 앞에 넣으면 모듈 명.__doc__ 로 검색가능  한문장으로 그룹화(;) : 여러문장을 ;로 연결해서 한 문장으로 만들 수 있음
  • 94. 문장 구분- doc 처리 모듈 내부에 모듈에 대한 설명이 필요할 경우 넣는 법 >>> import doctest hello world >>> doctest.__doc__ 'nCreated on Fri Jan 08 14:46:31 2016nn@author: 06411n' >>> # doctest.py # -*- coding: utf-8 -*- """ Created on Fri Jan 08 14:46:31 2016 @author: 06411 """ print("hello world ") 모듈 처리모듈 작성
  • 96. 변수(Variable) 변수는 객체를 관리하기 위한 참조를 관리하는 공간 즉, 변수는 객체를 가리키는 것 변수 내의 값 수치값 문자열 컨테이너 함수 클래스 튜플 리스트 딕션너리 집합 변수 Variable 객체의 참조 즉, 주소 저장 Variable 정의= 값 할당 리터럴(객체)
  • 97. 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 변수 정의( 할당) 할당 연산자를 이용하여 값을 변수에 할당. 실제 값의 참조가 변수에 보관
  • 98. Assignment & Type inference 파이썬 언어는 동적 타입을 체크하므로 주어진 타입을 추정해서 처리 I = 1 l = “string” l = 1.1 l은 변수이지만 변수 정의와 변수 할당이 동시에 된다. 변수에 할당시 타입을 추정해서 동적으로 정해진다. 파이썬에서 연속적으로 할당시 변수에 저장된 타입이 변경된다.
  • 99. Variable 삭제 Context 내에서 변수 삭제. del 변수명, del(변수명) 으로 삭제 >>> a= 1 >>> b =1 >>> a 1 >>> b 1 >>> del a >>> del(b) >>> a Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'a' is not defined >>> b Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'b' is not defined >>>
  • 101. Building block  Expression  Function  Object  Variable : point to object  Command
  • 102. Expression An expression is a combination of values, variables, and operators. 표현식을 선언해도 실제 정의되는 것이 객체이므로 별도의 블록이 유지 됨 >>> (i for i in l) <generator object <genexpr> at 0x06521E68> >>> dir((i for i in l)) ['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'gi_code', 'gi_frame', 'gi_running', 'next', 'send', 'throw'] >>>
  • 103. 지역변수와 전역변수 동적 데이터 타입 : 변수에 값이 할당될 경우 데이터 타입이 확정됨 변수는 이름공간 내에서 관리되면 변수는 동적으로 할당이 가능하다. 변수 검색 기준은 Local > Global > Built-in 영역 순으로 찾는다 Locals()와 globals() 함수를 이용해서 검색 >>> p = 100 >>> >>> def add(x,y) : … p =0 … print(locals()) >>> globals() >>> 함수내 파라미터와 그 내부에 정의된 변수 함수 외부 변수는 전 역변수
  • 104. Variable Bound/unbound 변수는 할당될 때 Binding 됨 >>> i =0 >>> i = i + 1 >>> i 1 >>>I = I + 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'i' is not defined 어휘분석에 따른 할당 될 경우 I + 1 부터 처리시 Unbinding 에러가 발생함 (NameError: name 'i' is not defined)
  • 106. Namespace 파이썬은 모듈, 패키지, 프로젝트 등의 단위로 작업공간을 두고 name을 기준으로 식별한다. 모듈, 패키지, 프로젝트 단위로 동일한 name을 가진 변수, 클래스 객체, 함수, 값 객체 등을 관리 해서 이중으로 발생하지 않도록 처리
  • 107. Namespace 관리 기준 Import로 패키지를 포함한 모듈을 호출하여 모듈처리 시 식별이 명확하도록 작업공간을 분리 프로젝트는 pythonpath를 기준으로 관리해서 로드한다. 공통 기능은 별도의 모듈로 분리해서 프로젝트를 분리해서 사용해야 이름공간이 충돌을 방지 할 수 있다 모든 객체이므로 이름공간관리 프로젝트 패키지 패키지 모듈 함수 클래스
  • 108. Namespace 확인하기 Dir() 함수 : 패키지, 모듈 등 네임스페이스 관리를 List로 표시 __dict__ : 객체 네임스페이스를 관리 사전으로 표 시 >>>dir() >>>dir(패키지) >>>객체이름.__dict__ >>>
  • 109. Object Namespace 흐름 Base class class instance instance instance 상속 인스턴스 생성 Dict{} Dict{} Dict{} Dict{} Dict{} Namespace 검색 객체는 자신들이 관리 하는 Namespace 공간 을 생성하며 객체 내의 속성이나 메 소드 호출시 이를 검색 해서 처리
  • 110. function Namespace 흐름 Namespace 검색 함수는 내부의 로직 처 리를 위한 Namespace 를 별도로 관리한다. 내부함수가 실행되면 외부함수 Namespace 를 참조하여 처리할 수 있다. 하위에서 상위는 참조 가 가능하나 상위에서 하위는 참조가 불가 함수 내부에서 locals()/globals() 관 리 영역 참조가능 모듈 외부함수 내부함수 내부함수 내부함수 영역 참조 영역참조 Dict{} Dict{} Dict{} Dict{} Dict{} Built-in Dict{} 영역 참조
  • 111. Namespace 기준  프로젝트  패키지  모듈  함수  클래스/인스턴스 객체 - 클래스 객체는 클래스 멤버들에 대한 관리할 경우에만 이름 공간 역할을 수행
  • 113. Statement Statement Description if statements 조건식 결과가 true 일 경우만 처리 if...else statements 조건식 결과가 true 일 경우는 if 내의 블럭처 리하고 false 일 경우 else 내의 블록 처리 nested if statements If와 elif 조건식 결과가 true 일 경우 블럭처리 하고 모든 조건식이 false 일 경우 else 블럭처 리
  • 114. For Statement 파이썬에서는 for in (sequence 타입)으로 처리함 For 문을 처리하고 추가적으로 처리할 것이 필요하면 else 구문을 이용하여 처리함
  • 115. Loop Statement Loop Type Description while loop 조건식이 true 일 경우에 실행 for loop sequence 타입에 대해 순환하여 처리 nested loops 순환내에 내부적인 순환조건을 만들 경우 외부 순환에 맞춰 내부 순환이 반복하여 실행
  • 116. 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문을 사용하 지 않아도 처리가 끝나면 클로즈가 자동으로 됨
  • 117. Break Statement 기존 control flow를 강제로 빠져나갈 경우 필요 for x in range(0, 5): print(x) if(x == 6): break else: print("else")
  • 118. Continue Statement 기존 control flow를 처리시 조건이 맞을 경우 처 음으로 돌아가서 계속 실행할 수 있도록 처리 >>> for i in [1,2,3,4,5] : ... if i == 2 : ... continue ... print i ... 1 3 4 5
  • 119. Pass Statement 처리가 필요없는 블록이 필요할 경우 pass문을 사용 하여 처리하지 않음 Continue 문장과의 차이점은 pass문은 현재 실행이 없다는 것을 의미만 함 >>> for i in [1,2,3,4,5] : ... if i == 2 : ... pass ... print i ... 1 2 3 4 5
  • 120. else Statement For/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
  • 122. 모듈 모듈이란 함수나 변수들, 또는 클래스들을 모아놓은 파일 파이썬이 모듈은 하나의 객체이면서 하나의 이름공간을 구성해서 내부 속 성에 대한 처리 방안을 제시한다. 모듈 내의 속성에 대한 접근은 점(.) 연산자를 통해 접근 # 모듈 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.apple() print mod.tangerine"
  • 123. 모듈 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 ’)
  • 124. 모듈 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 ’)
  • 125. if __name__ == "__main__": Command 창에서 모듈을 호출할 경우 __name__ 속성에 “__main__” 으로 들어감 Command 창에서 실행하면 현재 호출된 모듈을 기준으로 실행환경이 설정되기 때문에 “__main__” 이 실행환경이 기준이 됨
  • 126. 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 시 실행되는 영역
  • 127. 모듈 –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
  • 128. 패키지 패키지(Packages)는 도트('.')를 이용하여 파이썬 모듈을 계층적(디렉토리 구조)으로 관리 절대경로 import game.sound.echo # 패키지.패키지.모듈 from game.sound import echo from game.sound.echo import echo_test # 패키지.패키지.모듈 한 후 모듈속성 정의 상대경로 import .echo # 현재 패키지에 모듈을 import import ..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
  • 129. 패키지 예시 (1) 1. Kakao 프로젝트는 pythonpath에 등록 2. account 패키지 생성 3. account 패키지 내에 account.py 생성
  • 130. 패키지 예시 (2) 1. myproject 프로젝트는 pythonpath에 등록 2. add_test.py 생성 3. account.account를 import 하여
  • 131. 모듈 :pythonpath 등록 모듈에 대한 검색에서 오류가 발생할 경우 pythonpath에 현재 디렉토 리 위치를 추가해야 함 set PYTHONPATH=c:python20lib;
  • 132. 모듈 : ide에서 path 등록 실제 다양한 패키지를 사용할 경우 각 패키지를 등록해야 한다. #path >>> import sys >>> sys.path ['', 'C:WindowsSYSTEM32python34.zip', 'c:Python34DLLs', 'c:Python34lib', 'c: Python34', 'c:Python34libsite-packages'] # 현재 작성된 모듈의 위치 등록 >>> sys.path.append("C:/Python/Mymodules") >>> sys.path ['', 'C:WindowsSYSTEM32python34.zip', 'c:Python34DLLs', 'c:Python34lib', 'c:Python34', 'c:Python34libsite-packages', 'C:/Python/Mymodules'] >>> >>> import mod2 >>> print(mod2.sum(3,4)) # 결과값 7
  • 135. 함수 함수 정의와 함수 실행으로 구분 함수를 실행(호출)하기 전에 모듈 내에 함수 정의를 해야 함 #함수 정의 def 함수명(인자) 구문블럭(:) 함수 내부 로직 #함수 실행 함수명(인자) 함수 객체 함수 인자 객체 함수 명 (참조)
  • 136. 함수 내부 구조 알아보기 함수가 정의되면 함수 코드도 하나의 객체로 만들어짐 간단히 함수에 대한 로컬변수 확인해 봄 >>> def add(x,y) : ... return x+y ... >>> #함수정의에 대한 내부 구조 >>> add.func_code.co_varnames ('x', 'y') >>> >>> # 함수코드는 bytecode로 나타남 >>> add.func_code.co_code '|x00x00|x01x00x17S' >>>
  • 137. 함수 – 메모리 생성 규칙  함수 호출 시 마다 Stack에 함수 영역을 구성하 고 실행됨  함수를 재귀호출할 경우 각 호출된 함수 별로 stack영역을 구성하고 처리 함수정의 함수호출 1 함수호출 2 함수호출 3 함수호출 4 Stack 제일 마지막 호출된 것을 처리가 끝 나면 그 전 호출한 함수를 처리load
  • 138. 함수 – 메모리 생성 예시 정의된 함수에서 실제 함수를 실행시 함수 인스턴스 를 만들어서 실행됨 funcs = [] for i in range(4): def f(): print I # 함수 인스턴스를 추가 funcs.append(f) print funcs i =0 for 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 1 None 46309104 2 None 46309296 3 None 46363504 4 None 함수 생성된 개수만큼 생성됨 레퍼런스를 정수로 변환처리
  • 139. 함수 변수 Scoping 함수에 실행하면 함수 내의 변수에 대한 검색을 처리. 검색 순은 Local > global > Built-in 순으로 호출 Global/nonlocal 키워드를 변수에 정의해서 직접 상위 영역을 직접 참조할 수 있다 globalBuilt-in 함수 Scope 함수 Namespace local 내부함수 local
  • 140. 함수-Namespace  함수내의 인자를 함수 이름공간으로 관리하므로  하나의 dictionary로 관리  함수 인자는 이름공간에 하나의 키/값 체계로 관 리  함수의 인자나 함수내의 로컬변수는 동일한 이름 공간에서 관리  locals() 함수로 함수 내의 이름공간을 확인할 수 있음 #
  • 141. 함수-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()) 함수 외부 환경에 대한 변 수들을 관리하는 이름공간
  • 142. 함수 결과 처리-return/yield  함수는 처리결과를 무조건 처리한다.  Return 이 없는 경우에는 None으로 결과를 처리  함수 결과는 하나의 결과만 전달 • 여러 개를 전달 할 경우 Tuple로 묶어서 하나로 처리한다.  return 를 yield로 대체할 경우는 Generator가 발생 • 함수가 메모리에 있다가 재호출(next())하면 결과값을 처리
  • 144. 함수-Namespace : 인자관리 파이썬은 함수 인자와 함수 내의 로컬 변수를 동일 하게 관리. 함수 인자와 함수 내의 로컬변수명이 같은 경우 동 일한 것으로 처리 #함수 정의 def add(x, y) : return x+y #함수 실행 add(1,2) # 3 을 return Add 함수 내의 로컬 영역에 인자를 관리 하는 사전이 생기고 {‘x’: None, ‘y’:None} Add 함수 내의 로컬 영역에 인자에 매핑 {‘x’: 1, ‘y’: 2}
  • 145. 함수 인자 – 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 함수정의 인자에 변경가능한 값을 할당하지 않 음
  • 146. 외부변수를 함수 변수 활용 함수의 인자를 함수 외부와 내부에서 활용하려면 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]
  • 147. 함수-초기값/인자변수에 값할당 함수 내의 인자를 별도의 이름공간에 관리하므로 고 정인자일 경우에도 이름에 값을 할당 가능 #함수 정의 def add(x=10, y) : return x+y #함수 실행 add(1,y=20) # 21 을 return add 함수 내의 로컬 영역에 인자를 관리 하는 사전이 생기고 {‘x’: 10, ‘y’:None} add 함수 내의 로컬 영역에 인자에 매핑 {‘x’: 1, ‘y’: 20}
  • 148. 함수-가변인자-값(*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) }
  • 149. 함수-가변인자-키/값(**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} }
  • 151. 함수 반복 호출 함수도 호출 방법에 따라 다양한 구현 및 처리가 가 능 연속(재귀)호출 특정 시점 호출 부분 호출 함수를 인자값을 바꿔가면 처리가 완료 될 때까지 연속해서 호출하여 처리 함수를 구동시켜 필요한 시점에 호출하여 결과 처리(iteration, generation) 함수를 인자별로 분리하여 호출하면서 연 결해서 결과를 처리
  • 152. 함수 - 재귀호출 함수 정의시 함수가 여러 번 호출될 것을 기준으로 로직을 작성해서 동일한 함수를 지속적으로 처리할 도록 호출 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, "): ",result) return result print(factorial(5)) 자신의 함수를 계속 호출하면 stack에 새로운 함수 영역이 생겨서 처리한다
  • 153. 함수 – 시점 호출 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 >>>
  • 154. 함수 – 시점 호출 :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
  • 155. 함수 – 시점호출 : 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 >>>
  • 156. 함수- 부분호출 : 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) 출력
  • 157. 함수- 부분 호출 : partial 파이썬에서는 partial 함수를 제공해서 함수를 분할 하여 처리함 from functools import partial def 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) 출력
  • 159. 함수를 내부함수 정의 함수는 사용하기 전에 정의해서 사용. 함수 내에 다시 함수를 정의하여 사용 # 외부 함수 정의 def outer() : # 내부 함수정의 def inner() : pass # 내부함수 실행 후 결과 전달 # 결과값은 아무것도 없음 return inner()
  • 160. 함수를 내부함수 처리 함수 내부에 함수를 정의하고 함수 내부에서 실 행하여 처리 def greet(name): #내부 함수 정의 def get_message(): return "Hello “ #내부함수 실행 result = get_message()+name return result #외부함수 실행 print greet("Dahl") 함수 내부에 기능이 필요한 경우 내부 함 수를 정의하여 호출하여 처리
  • 161. 내외부 함수에 대한 변수 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()
  • 163. First Class Object(1) 일반적으로 First Class 의 조건을 다음과 같이 정의한다.  변수(variable)에 담을 수 있다  인자(parameter)로 전달할 수 있다  반환값(return value)으로 전달할 수 있다  1급 객체(first class object) #함수를 변수에 할당 func = add print 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> 10 10
  • 164. 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)
  • 165. 함수를 변수에 할당 함수도 객체이므로 변수에 할당이 가능 함수 객체 함수 인자 객체 함수명 (참조주소) 함수 정의 변수 변수에 할당 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) 변수는 참조를 저장하므로 함수의 참조도 변수에 저장되고 실행연 산자( () )를 이용하여 처리 가능
  • 166. 함수를 파라미터로 전달 함수도 하나의 객체이며 데이터 타입이므로 파라 미터인자로 전달이 가능 외부에 함수를 정의하고 실행함수에 파라미터로 전달 후 실행함수 내부에서 실행 #파라미터 전달 함수 정의 def greet(name): return "Hello " + name #실행 함수 정의 def call_func(func): other_name = “Dahl“ #파라미터 전달된 함수 실행 return func(other_name) #함수 실행 print call_func(greet)
  • 167. 함수 결과값을 함수로 전달 함수 결과값을 함수정의된 참조를 전달해서 외부 에서 전달받은 함수를 실행하여 처리 #실행함수 정의 def compose_greet_func(): #내부함수 정의 def get_message(): return "Hello there!“ #내부함수를 함수처리결과값으로 전달 return get_message #함수실행 : 결과값은 함수의 참조 전달 #함수를 변수에 할당 greet = compose_greet_func() #함수 실행: 변수에 할당된 내부함수가 실행됨 print greet()
  • 169. 함수 - Lambda Lambda는 단순 처리를 위한 익명함수이고 return을 표시하지 않는다. 익명함수를 정의하고 실행하지만 리턴 결과는 한 개만 전달 할 수 있다. Lambda 인자 : 표현식 함수 객체 함수 인자 객체 함수명 미존재 (참조주소) 익명함수 정의 변수 필요시 변수에 할당
  • 170. 함수 – Lambda 예시 Lambda는 표현식시 2개의 리턴 값이 생기므로 에러가 발생함 표현식에서 2개 이상 결과를 나타내려면 tuple 처리해야 함 >>> x = lambda x,y : y,x Traceback (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)
  • 172. 함수 – Closure : context 외부함수 내의 자유변수를 내부함수에서 사용하면 기존 외부함 수도 내부함수가 종료시까지 같이 지속된다. 함수 단위의 variable scope 위반이지만 현재 함수형 언어에서는 함수 내의 변수를 공유하여 처리할 수 있도록 구성하여 처리할 수 있도록 구성이 가능하다. 외부함수 내부함수 외부함수 이름공간 내부함수 이름공간 Closure context 구성 내부함수 변수 검색 순 서는 내부함수 이름공 간 -> 외부함수 이름 공간
  • 173. 함수 – 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_contents print 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__는 튜플로 구성되어 자유변수에 대해 객체로 구성됨
  • 174. 함수 – 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) 자유변수가 immutable 일 경 우 내부함수에 생 기지만 변경할 수 없으므로 에러처 리 Locals()함수를 이 용하여 함수에서 관리하는 변수를 출력 outer {'n': 4} inner {'x': 5, 'n': 4}
  • 175. 함수 – Closure : 자유변수(2) 변수는 Mutable 값과 Immutable 값이 binding되면서 정의되므로 내부함수에서 외부함수의 변수(immutable)에 재할당 시 unboundlocalerror 발생시 해결 방안  내부함수에 키워드 nonlocal를 변수에 사용  외부함수에 mutable 값을 할당한 변수를 사용(리스트, 사전으로 정의) 외부함수 Context 내부함수 Context Local Local Int Float string Immutable 객체 외부함수의 변수를 변경하려면 외부함수 context 에서 처리 되어야 함 함수의 인자 전달시 동일한 원칙이 발생
  • 177. 함수 연속 실행 함수 chian은 함수를 결과값으로 받고 실행연산자 (parameter)를 연속하면 함수들을 계속 실행함 def chain(obj) : return obj def cc(obj): print obj chain(cc)('str') 함수1 실행 하고 함수 2실행 #결과값 str
  • 179. 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]
  • 180. map 함수 map(f, iterable)은 함수(f)와 반복가능한 자료형(iterable) 을 입력으로 받아 입력 자료형의 각각의 요소가 함수 f에 의해 수행된 결과를 묶어서 리턴하는 함수 # 파이썬 2 및 파이썬 3 # 5개 원소를 가진 리스트의 제곱하여 변환 list(map(lambda x: x ** 2, range(5))) # 결과값 : [0, 1, 4, 9, 16]
  • 181. 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 6 reduce 6
  • 182. 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된 결 과를 리턴하는 함수
  • 184. Decorator 사용 기법  함수 Chain : 함수를 결과 값 처리  고차함수  클로저  functools 모듈의 wraps함수 사용
  • 185. Decorator : functools 사용이유  functools 모듈의 wraps함수 사용을 할 경우 __doc__/__name__이 삭제되지 않고 함수의 것 을 유지
  • 186. Decorator 처리 흐름 Decorator 함수 내부에 내부함수를 정의해서 파라미터로 받은 함수를 wrapping하여 리턴 처리하고 최종으로 전달함수를 실행  함수Chain 처리(버블링) 함수 1 함수 2 함수 3 (전달함 수) 함수2(함수3) 함수 3 실행 함수1(함수2(함수3)) @f1 @f2 Decorator 순서 함수1(함수2(함수3))(전달변수) 함수호출 순서
  • 187. 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_return def r_print() : print (" r print ") r_print() 외부함수 전달함수 함수 실행
  • 188. Decorator :단순 wrapping 예시  Decorator 되는 함수에 파라미터에 실행될 함수를 전달되고 내부함 수인 wrapping함수를 리턴  Wrapping 함수 내부에 전달함수를 실행하도록 정의  데코레이터와 전달함수 정의  전달함수를 실행하면 데코레이터 함수와 연계해서 실행 후 결과값 출력 def common_func(func) : def wrap_func() : return func() return wrap_func @common_func def r_func() : print " r func " 데코레이터 함수 정의 전달 함수 및 데코레이션 정의 함수 할당 및 실행 r_func() #처리결과 r func
  • 189. 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_f def add_1(x,y): return x+y 데코레이터 함수 정의 전달 함수 및 데코레이션 정의 함수 할당 및 실행 #데코레이터 호출 x = add_1(5,5) print(' decorator ', x) #함수 처리 순서 v = outer_f(add) v(5,5)
  • 190. Functools Module functools.wraps(wrapped[, assigned][, updated]) 을 이용하여 데코레이션 처리 from functools import wraps def my_decorator(f): @wraps(f) def wrapper(*args, **kwds): print 'Calling decorated function' return f(*args, **kwds) return wrapper @my_decorator def example(): """Docstring""" print 'Called example function' example() 1. Functool를 import 처리 2. @wraps(전달함수) 3. Wrapper로 함수에 파 라미터 전달 4. 데코레이션 정의 5. 전달함수 작성 6. 전달함수 실행
  • 191. 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")
  • 192. Functools Module functools.wraps(wrapped[, assigned][, updated]) 을 이용하여 데코레이션 처리 from functools import wraps def my_decorator(f): @wraps(f) def wrapper(*args, **kwds): print 'Calling decorated function' return f(*args, **kwds) return wrapper @my_decorator def example(): """Docstring""" print 'Called example function' example() 1. Functool를 import 처리 2. @wraps(전달함수) 3. Wrapper로 함수에 파 라미터 전달 4. 데코레이션 정의 5. 전달함수 작성 6. 전달함수 실행
  • 193. 복수 Function decorator 순서 실행 func을 호출시 실행 순서는 decorate1(decorate2(decorat3(func)))로 자동 으로 연결하여 처리됨 #decorate1 def decorate1 : pass #decorate2 def decorate2 : pass #decorate3 def decorate3 : pass @decorate1 @decorate2 @decorate3 def func : pass
  • 194. Functools Module: 파라미터 데코레이터 파라미터를 처리하기 위해 파라미터 처리하는 함수를 하나 더 처리 from functools import wraps def 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. 전달함수 실행
  • 195. 복수 Function decorator 예시 함수 호출 순서는 f1(f2(add))(5,5)로 자동으로 연결하여 처리됨 #decorator 함수 1 def 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 @f2 def 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 함수 정의 함수 실행
  • 196. CLASS
  • 198. 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> ... ... 클래스에서 객체 생성하기
  • 199. 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 내의 인스턴스 메소드 파이썬에서 클래스는 하나의 타입이면서 하나의 객체이다. 실제 인스턴스 객 체를 만들 수 있는 타입으로 사용
  • 200. Int Class 설명 예시 >>> dir(int) ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__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', 'denominator', '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 생성
  • 201. Class Object & instance Class Object는 인스턴스를 만드는 기준을 정리한다. 클래스를 정의한다고 하나의 저장공간(Namespace) 기준이 되는 것은 아니다. - 클래스 저장공간과 인스턴스 저장공간이 분리된다 User defined Class Instance Instance Instance Built-in Class 상속 인스턴스화 Object Scope Object Namespace
  • 203. Class Member Class 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} 인스턴스 메소드
  • 204. Predefined Class Attributes 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.
  • 205. Instance Member Instance 생성시 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} # 인스턴스 객체 관리 영역
  • 206. 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
  • 208. Class 멤버 접근자 - cls 클래스 객체의 변수나 메소드 접근을 위해 cls 키워 드 사용
  • 209. Instance 멤버 접근자-self 인스턴스객체 메소드의 첫 인자는 Self를 사용하여 각 인스턴스별로 메소드를 호출하여 사용할 수 있 도록 정의
  • 210. Method- 인스턴스 객체 클래스 객체에서 생성되는 모든 인스턴스 객체에서 활용되므로 클래스 이름공간에서 관리 메소드 첫 파라미터에 self라는 명칭을 정의
  • 211. Method- 클래스 decorator 클래스 객체에서 처리되는 메소드를 정의한다. 클래스 메소 드는 첫번째 파라미터에 cls를 전달한다. 장식자 @classmethod : 클래스 함수 위에 표시-Python 2.x 함수 classmethod() : 별도 문장으로 표시 – Python 3.x 인스턴스 객체도 호출이 가능
  • 212. Method- 정적 decorator 클래스 객체로 생성된 모든 인스턴스 객체가 공유하여 사용 할 수 있다. 장식자 @staticmethod : 정적함수 위에 표시 – Python 2.x 함수 staticmethod()는 별도의 문장으로 표시 –Python 3.x 정적메소드는 파라미터에 별도의 self, cls, 등 객체에 대한 참조값을 전달하지 않아도 됨 인스턴스 객체에서도 호출이 가능
  • 213. 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.empCount 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 생성 및 호출
  • 214. 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
  • 215. 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)
  • 216. Method & Object Chain
  • 217. 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() 객체들간의 연결고리가 있을 경우 메소드 결과값을 객체로 받아 연속적으로 실행하도록 처리
  • 218. 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 관계)가 있을 경 우 메소드 결과값을 객체로 받아 연속적으로 실행하도록 처리 객체.내부객체.메소 드 처리 #결과값 a b B instance method None
  • 220. 생성자-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) 생성자 정의 인스턴스 객체 생성 생성자와 자동으로 연계
  • 221. 소멸자- 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 = pt1 pt3 = pt1 print id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts del pt1 del pt2 del pt3 소멸자 정의 소멸자 활용
  • 223. 클래스 구조 알기(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 클래스 구조
  • 224. 클래스 구조 알기(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
  • 225. 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 처리
  • 226. Class & instance namespace Class 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 정의
  • 228. Members(변수) Access Class/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()
  • 229. 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 내장 객체 내장 객체
  • 230. Members(메소드) Access Class 정의시 인스턴스 메소드 정의를 하면 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()
  • 231. Members(메소드) Access-세부 인스턴스에서 인스턴스메소드 호출하면 실제 인스 턴스 메소드 실행환경은 인스턴스에 생성되어 처리 >>> #인스턴스에서 실행될 때 바운드 영역이 다름 >>> # is 연산자는 동일 객체 체계 >>> cobj.f is C.__dict__['f'] False >>> >>> C.__dict__ {'classattr': 'attr on class', '__module__': '__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 내장 객체 내장 객체
  • 232. Controlling Attribute Access Instance의 Attribute에 대한 접근을 할 수 있는 내 부 함수 __getattr__(self, name) __setattr__(self, name, value) __delattr__(self, name) __getattribute__(self, name)
  • 233. 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__
  • 235. Inheritance 상속은 상위 클래스를 하나 또는 여러 개를 사용하는 방법 class 상위 클래스명 : pass class 클래스명(상위 클래스명) : pass 상속 정의시 파라미터로 상위 클래스명을 여러 개 작 성시 멀티 상속이 가능함 class 클래스명(상위 클래스명, 상위 클래스명) : pass