View
127
Download
9
Category
Preview:
DESCRIPTION
Advanced Topics in Python. SPARCS 05 김준기 2010. 4. 8. Contents. Class Details & Inheritance Unicode vs . String More about Functions Functional Programming Review on Modules Python Packages & Libraries Extra Things. Class. 다들 복습하셨겠죠 ?. Class. 기억이 안 난다구요 ?. 자료형. 그럼 이건 ?. Class. - PowerPoint PPT Presentation
Citation preview
Advanced Topics in Python
SPARCS 05 김준기2010. 4. 8
Contents
▶ Class Details & Inheritance▶ Unicode vs. String▶ More about Functions▶ Functional Programming▶ Review on Modules▶ Python Packages & Libraries▶ Extra Things
Class
다들 복습하셨겠죠 ?
Class
기억이 안 난다구요 ?
자료형
그럼 이건 ?
Class
class = type defined as data + operations
instance = an object whose type is a cer-tain class
Class
그 다음엔 ?
class person(object): def __init__(self, …): … def __str__(self, …): …
강성훈
Class
Method 를 추가해보자
class person(object): def __init__(self, …): … def __str__(self, …): … def dday_to_birthday(self): …
Class
from datetime import dateclass person(object): def __init__(self, …): … def __str__(self, …): … def dday_to_birthday(self): return date(self.year, self.-month, self.day) – date.to-day()>>> date.today()datetime.date(2010, 4, 8)>>> joongi.dday_to_birthday()datetime.timedelta(-8367)
Class Details
▶ 미리 정의된 이름들__init__, __str__, …?
▶ date 자료형을 뺄셈하면 뭐가 나오나 ?
class date(object): def __sub__(self, other): return timedelta( self.toordinal() – \ other.toordinal() )
Class Details
▶ 미리 정의된 이름의 목록과 명세는 여기 :http://docs.python.org/reference/datamodel.html#special-method-names 참고 : 앞으로 배울 Django 에서도 이거
많이 써서 만들었습니다 .용자는 소스코드를 뜯어보세요 ~ ㅋㅋ
▶ 영어 레퍼런스 읽기를 두려워하지 마세요 !
Class Details
C++/Java 를 보면 이런 것도 있던데…요 ?
public static void main(String args[]) {…}private int myFunction(int x) {…}protected void printToSomething(BufferedWriter writer) {…}
Class Details
▶ 결론 : Python 엔 그런 거 없뜸 ( 모두 public)
▶ 하지만…
‘ _’ 로 시작하는 class, function 제외
▶ 일반적으로 private 은 ‘ _’ 로 시작하는 이름으로 표시하는 것이 관습
from mypackage import *
Class Details
▶ 잠깐 ! static 도 없나요 ? 사실 필요는 없어요 . (class = names-pace?)
▶ 지금까지 본 건 모두 instance methodstatic method 도 있습니다 .class person(object): @staticmethod def ask_name(man): …
>>> person.ask_name(joongi)
Class Details
▶ 비슷한 (?) 것으로 class method
cls 는 person 자료형 자체 전달 상속 처리할 때 유용
class person(object): @classmethod def ask_name(cls, man): …class newtype(person): …
>>> person.ask_name(joongi)>>> newtype.ask_name(joongi)
Class Inheritance
상속 ?그거 하면 세금도 내나요 ?
Class Inheritance
▶ Extend vs. Inherit 사실은 같은 개념 (subtype)
class person(object): …class newtype(person): …
>>> joongi = person()>>> type(joongi)<class 'person'>>>> android = newtype()>>> type(android)<class 'newtype'>
Class Inheritance
▶ 상속 관계 알아보기
“I’m your base!”
>>> type(joongi).__bases__(<type 'object'>,)>>> type(android).__bases__(<class 'person'>,)
Class Inheritance
▶ static method vs. class method class method 는 어떤 클래스로부터
호출되나 알 수 있다 .
class person(object): @classmethod def doit(cls, action): print '%s!! by %s' % (action, cls.__name__)class newtype(person): pass>>> person.doit('shout')shout!! by person>>> newtype.doit('shout')shout!! by newtype
Unicode vs. String
▶ Encoding 어떤 ‘정보’를 컴퓨터에서 실제로 ‘어떻게’
표현할 것인가 ?▶ String
이상 : ‘ 문자’의 나열 현실 : 그냥 메모리에 1byte 씩 때려박기
▶ Unicode 세계 공통의 ‘문자 집합’ 정의
Unicode vs. String
▶ String Encoding ‘ 문자’들을 메모리에 ‘어떻게’ 때려박을까 ?
▶ CP949, UTF-8, ISO-8859-1 (Latin1) 여러분이 자주 보게 될 encoding 이름
▶ Unicode Encoding Unicode 에 속한 문자들을 어떻게 표현하나 ? UTF-7, UTF-8, UTF-16, UTF-32, …
Unicode vs. String
▶ 자 , 그럼 현실을 들여다봅시다 .
# coding: cp949print ' 김준기 'print repr(' 김준기 ')
김준기'\xb1\xe8\xc1\xd8\xb1\xe2'
Unicode vs. String
▶ 다른 평행현실은 ?
깨진 글자가 보였다면 윈도 명령 프롬프트 ?
# coding: utf8print ' 김준기 'print repr(' 김준기 ')
源 � 以 � 湲'\xea\xb9\x80\xec\xa4\x80\xea\xb8\xb0'
Unicode vs. String
▶ 특이점
어째서 깨지지 않았을까 ?
# coding: utf8print u' 김준기 'print repr(u' 김준기 ')
김준기u'\uae40\uc900\uae30'
Unicode vs. String
▶ 사실은…
어라 , 똑같네 ?
# coding: cp949print u' 김준기 'print repr(u' 김준기 ')
김준기u'\uae40\uc900\uae30'
Unicode vs. String
▶ Python 엔 2 가지 종류의 문자열 자료형이 있습니다 .
>>> type(' 김준기 ')<type 'str'>>>> type(u' 김준기 ')<type 'unicode'>
Unicode vs. String
▶ unicode 가 안 깨졌던 비밀은… 소스파일 읽을 때 unicode 로 자동 변환(u'' 쓴 것만 , “coding” 설정에 따라 )
print 할 때 str 로 자동 변환
class unicode(object): def __str__(self): # print 할 때 호출됨 return self.encode(sys.getfilesystemencoding())
Unicode vs. String
▶ 상호 변환하기
unicode object str object
.encode(encoding_name)
.decode(encoding_name)
>>> u' 김준기 '.encode('utf8')'\xea\xb9\x80\xec\xa4\x80\xea\xb8\xb0'>>> u' 김준기 '.encode('cp949')'\xb1\xe8\xc1\xd8\xb1\xe2'
Unicode vs. String
▶ 상호 변환하기
▶ unicode object 자체로는 입출력 불가 ! Python이 암시적으로 자동 변환하든 (print),
프로그래머가 명시적으로 변환하든 해야만 가능
>>> '\xea\xb9\x80\xec\xa4\x80\xea\xb8\xb0'.decode('utf8')u'\uae40\uc900\uae30'>>> '\xea\xb9\x80\xec\xa4\x80\xea\xb8\xb0'.decode('cp949')Traceback (most recent call last): File "<stdin>", line 1, in <module>UnicodeDecodeError: 'cp949' codec can't decode bytes in position 2-3: illegal multibyte sequence
Unicode vs. String
▶ 흔히 많이 하는 실수 unicode 와 str 섞어쓰기
암시적 변환이 편리하지만 버그 발생률 높음예 ) Database / System 인코딩 설정이 다른 상황에 암시적 변환이 결합하면…
▶ 조금 귀찮지만 , 항상 unicode 를 쓰자 .
(Python 3.0 부터는 unicode 가 기본 !)
'This is my precious name, %s.' % u'김준기 '
More about Functions
▶ 선택적 인자 (optional argument)
▶ Positional argumentsdef download(url, exit_on_complete=True): …
def sum(*args): result = 0 for item in args: # args is a tu-ple. result += item return result>>> sum(1,2,3,5,8)19
More about Functions
▶ Keyword argumentsdef animate(**kwargs): # kwargs is a dict. duration = kwargs.get('duration', 100) replay = kwargs.get('replay', False) …>>> animate()(animation with duration 100, no replay)>>> animate(replay=True)(animation with duration 100, replay)>>> animate(replay=True, duration=500)(animation with duration 500, replay)
More about Functions
▶ More complex exampledef create_person(name, *args, **kwargs): man = person(name, sum(*args), 1, 1) for k, v in kwargs.iteritems(): setattr(man, k, v) return man>>> create_person(u' 김준기 ', 1, 2, 3,... shoes_size=275)>>> create_person(u' 강성훈 ', 5, 6,... is_supercoder=True)
Functional Programming
▶ 저번 시간에 lambda 나왔습니다 .사실 이거 함수 (function) 입니다 .다만 문법 상 expression 으로 제한했을 뿐 .
Function = just a callable ob-ject
혹시 앞부분 기억한다면… 이런 것도 있어요 ~def __call__(self, *args): …
Functional Programming
▶ lambda 자주 사용하는 곳 map() : 개별 item 에 적용할 함수 filter() : 조건 만족 판단 함수 sort() : 대소 비교하는 함수
▶ Functional Programming 의 장점 ?임의의 함수를 인자로 전달하거나 다른 곳에 저장하여 유연하게 프로그래밍할 수 있습니다 .
Functional Programming
▶ Decoratorfunction 을 장식하여 장식된 function을 반환하는 function
class person(object): @staticmethod def ask_name(man): …
class person(object): def ask_name(man): … ask_name = staticmethod(ask_name)
Functional Programming
▶ Decorator Example: CS101 WTFdef print_return(func): def decorated(*args, **kwargs): ret = func(*args, **kwargs) print ret return ret return decorated
class person(object): @print_return def get_name(self): return self.name
Functional Programming
▶ Decorator Example: CS101 WTF
▶ 실제 활용 예 (Django views)
>>> joongi = person(u' 김준기 ')>>> dummy = joongi.get_name() # without deco>>> dummy = joongi.get_name() # with deco김준기
from django.contrib.auth.decorators import login_required
@login_requireddef privileged_page(request): …
Functional Programming
▶ Decorator Example Improved
decorated 함수의 footprint 를 func 의 것으로 바꿔주는 효과로 Django view 목록 볼 때 편리함
from functools import wraps
def print_return_improved(func): @wraps(func) def decorated(*args, **kwargs): ret = func(*args, **kwargs) print ret return ret return decorated
Functional Programming
▶ Decorator Example Improved
보면 알겠지만 함수도 object 라서 여러 속성과 내부 method 들이 있습니다 .
>>> def myfunc(): pass>>> myfunc1 = print_return(myfunc)>>> myfunc2 = print_return_improved(myfunc)>>> myfunc1.__name__decorated>>> myfunc2.__name__myfunc
Functional Programming
▶ Generator: the secret of Pythondef range(n): thelist = [] for i in xrange(n): thelist.append(i) return thelistdef xrange(n): k = 0 while k < n: yield k k += 1 raise StopIteration()
Functional Programming
▶ List Generator Syntax
>>> [k+1 for k in xrange(10)][1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>>> [(k+1,j+1) for k in xrange(3) for j in xrange(3)][(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]>>> import os>>> [name for name in os.listdir('.') \... if not name.startswith('.')]
Modules
뭔가 추가할까 했는데 ,강성훈 슬라이드 보니 잘 해놨더라 =3
잠시 쉽시다 .
Packages
여러분이 모든 걸 직접 다 짜진 않겠죠 ?
Don’t reinvent the wheel!
Packages
▶ 외부 라이브러리 설치하는 방법 Debian/Ubuntu 등 리눅스 배포판에서
제공하는 패키지 설치 ( 보통 “ python-” 으로 시작 )
압축파일 받아서 푼 다음 수동설치$ sudo python setup.py install
python-setuptools 패키지 설치한 후$ sudo easy_install something
수동설치에 C/C++ 컴파일러 필요할 수 있음(python-dev, build-essentials 설치 )
Packages
▶ 외부 라이브러리가 설치되는 장소 Linux ( 배포판마다 다름 )/usr/lib/python2.6/site-packages/usr/lib/python2.6/dist-packages
WindowsC:\{Python 설치경로 }\Libs\site-pack-ages
▶ 설치 형태 python 소스코드 그대로 C/C++ 컴파일된 모듈 .egg 압축 파일
Packages
▶ 설치 장소 알아내는 팁
▶ 참고 *.py : source code *.pyc : pre-compiled bytecode *.pyo : optimized bytecode
>>> import somelib>>> somelib.__file__/usr/lib/python2.6/dist-packages/somelib/__init__.pyc
Packages
▶ 패키지 업데이트 : 보통 재설치하면 됨▶ 패키지 삭제
배포판 패키지 : apt/yum 등에서 삭제 easy_install 이용한 경우 , 불행히도…site-packages/*.pth 파일 및 그 안에 적힌 관련 파일 모두 찾아 수동 삭제
수동 설치한 경우는 당연히 수동 삭제 -_-
Packages
그럼 우리가 만들 순 없을까 ?
당연히 된다 .
… 다만 setup.py/egg 제작법 같은 건 아직 나도 몰라요 ;( 대충 distutils, setuptools 잘 구워삶으면 되는 듯 )
Packages
▶ Package 의 구조mylib
__init__.py
module1.py
module2.py
subdir1
__init__.py
module3.py
classes, functions, …
classes, functions, …
classes, functions, …
subdir2
__init__.py
module5.py classes, functions, …
module4.py classes, functions, …
Packages
▶ Absolute Imports
패키지 이름부터 모두 적는 방식
▶ Relative Imports
패키지 내에서 현재 module 위치를 기준으로 상대경로처럼 import 할 수 있다 .(Python 2.5 부터 지원 )
from mylib.subdir1.module4 import some-thing
from .module4 import somethingfrom ..module1 import somethingfrom ..subdir2.module5 import something
Extra Things
여러 사람이 같이 개발하면…
class person(object): def get_name(self): return self.name[:]class person(object): def getname(self): return self._name[ : ]
class Person (object) : def getName (self) : return self.name [ : ]
PEP-8
▶ Python Enhancement Proposals http://www.python.org/dev/peps/
▶ PEP-8: Style Guide for Python Code
왜 언어개발자들이 이걸 강조했을까 ?
PEP-8
▶ Indent: space 4 개▶ Space
block 시작하는 ‘ :’ 앞에서 뺌 function call, list/dict indexing/slicing 나타내는 괄호 /대괄호 앞에서 뺌
operator 앞뒤로는 1 개씩만 keyword argument 에 사용된 ‘ =’ 앞뒤는 뺌
PEP-8
▶ 줄바꿈 ‘;’ 이용한 명령어 한 줄 쓰기는 피하자 block 시작점 다음엔 반드시 !
▶ 주석 작성하기 여러 줄 주석은 코드와 동일하게 indent inline 주석은 최소 공백 2 개 띄우기
PEP-8
▶ 이름 짓기 Package/Module : lowercase Class : CapitalizedWords (aka CamelCase)
Functions : lowercase_with_underscore
• instance method 의 첫번째 인자는 항상 self• class method 의 첫번째 인자는 항상 cls
Variables : like functions Constants : ALL_CAPITAL_WITH_UNDERSCORE
PEP-8 on Vim
▶ ~/.vimrc
▶ ~/.vim/ftplugin/python.vim
…inoremap # X^H#filetype plugin on
set ts=4 sts=4 sw=4 expandtabset nocopyindent nocindent ai siset formatoptions=croql
docstring
▶ help() 배우셨죠 ? 써봤고 아패로도 계속 쓰길 바랍니다 .
우리가 작성한 코드에도 적용하려면 ?
docstring
▶ CS101 에서 이런 걸 배우셨을 텐데…
단순히 여러 줄 문자열 / 주석뿐만 아니라 ,모듈 , 클래스 , 함수에 대한 설명을 적는 데사용할 수 있습니다 .
'''some long long long multi-line code…'''
docstringclass person(object): u''' 사람을 나타내는 클래스 이름 , 생년월일을 저장할 수 있습니다 . ''' def get_name(self): u''' 사람의 이름을 반환합니다 .''' return self.name
>>> help(person)Help on class person in module <module>:
class person(__builtin__.object) | 사람을 나타내는 클래스 | 이름 , 생녈월일을 저장할 수 있습니다 .…
docstring
▶ Ooops!
Unicode docstring 을 표시할 때 기본값이 ascii 인sys.getdefaultencoding() 을 사용해서 생기는 문제
>>> help(person)Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Development\Python26\lib\site.py", line 429, in __call__ return pydoc.help(*args, **kwds)… File "C:\Development\Python26\lib\pydoc.py", line 1367, in temp-filepager file.write(text)UnicodeEncodeError: 'ascii' codec can't encode characters in posi-tion 78-80: ordinal not in range(128)
docstring
▶ Unicode docstring 인코딩 문제 해결법
/etc/python26/sitecustomize.py또는 (Python 2.6 이상이라면 )~/.local/lib/python2.6/site-packages/sitecus-tomize.py또는 (Windows 라면 )C:\{Python 설치경로 }\Libs\site-packages\sitecus-tomize.pyimport syssys.setdefaultencoding('utf8') # for Linux
import syssys.setdefaultencoding('cp949') # for Win-dows주의 : sys.setdefaultencoding() 은 파이썬 초기화 중일 때만 사용할 수 있습니다 .
docstring
▶ 작성하는 방법에 대한 권장 사항은 역시 PEP 를 참고하세요 !
http://www.python.org/dev/peps/pep-0257/
http://www.python.org/dev/peps/pep-0287/
and more…?
▶ 여러분이 알아두면 좋은 표준 라이브러리sys, os, os.path : 시스템 /디렉토리 / 파일 접근 관련codecs : encoding-aware 파일 입출력re : 대망의 정규표현식urllib, urllib2 : 다른 웹서버 접근datetime : 날짜 / 시간 관련math : 수학 함수들itertools, functools, operator : 파이썬 언어 기능 확장
shutil, glob : 좀더 편리한 디렉토리 / 파일 작업hashlib : md5, sha1 등의 hash 함수 제공unittest : 유닛테스트 기능xml.etree : XML 조작하기 (3rd party 로는 lxml 추천 )socket : 네트워크 통신 (TCP/IP)
and more…
▶ 여기서도 커버하지 못한 부분들 ㅠ _ㅠ Testing (with unittest/doctest) Debugging (with pdb) Metaclass
선배들한테 “ More Advanced” 세미나 해달라고 조르세요 ! ( 저 빼고 ) =3=3
▶ 사실 , 이상의 내용을 다 이해하려면3학년 전공 정도는 들어줘야…
Q&A드디어 끝났습니다
Recommended