파이선 문법 조금만더

Post on 14-Jul-2015

1.044 Views

Category:

Documents

3 Downloads

Preview:

Click to see full reader

TRANSCRIPT

파이선… 썬인가? 뭐 어쨌든

문법 조금만더

개발의 기초

내가 개발 좀 해봐서 아는데….

For 와 if

• 두 개만 있으면 다 된다…

라고 좀 해본분이 말씀하셨음

근데 지금은 뭐가 많다

파이써닉 ??

• 최대한 효율적인 소규모 코딩패턴

• 별거 아닌거 길게 쓰지 말자

• 짧은코드가 더 빠를수도 있다.

List Comprehension

학교에서 배운거

for(i=0 ; i < 10 ; i++)

{

arr[i]=doSomthing(i);

}

배운대로 한거

for i in range(10):

lst.append(doSomthing(i))

Pythonic

[doSomthing(i) for i in range(10)]

dJango

user_obj._group_perm_cache =

set(["%s.%s"% (ct, name)

for ct, name in perms])

왜?• 파이썬에서 루프 돌려서 리스트 만드는

건 비효율적

• 인터프리터가 매 루프마다 리스트의 변

화를 처리

• 어떤 요소를 다룰지 추적하기위한 카운

터를 유지해야함

이터레이터와 제너레이터

이터레이터는

두가지만 기억하세요

next, __iter__

class MyIterator(object):

def __init__(self, step):

self.step = step

def next(self):

"""Returns the next element."""

if self.step == 0:

raise StopIteration

self.step -= 1

return self.step

def __iter__(self):

"""Returns the iterator itself."""

return self

for el in MyIterator(4):print el

제너레이터

Range() VS xRange()그냥 함수

호출될때

리스트를 다 만듦

그때그때

필요한 만큼만

생성

리스트가 필요할때

• 파이스닉하게

• 찔끔찔끔

yield

def fibonacci():a, b = 0, 1while True:

yield ba, b = b, a + b

fib = fibonacci()

[fib.next() for i in range(10)]

def psychologist():

print 'Please tell me your problems'

while True:

answer = (yield)

if answer is not None:

if answer.endswith('?'):

print ("Don't ask yourself too much

questions")

elif 'good' in answer:

print "A that's good, go on"

elif 'bad' in answer:

print "Don't be so negative"

>>> free = psychologist()

>>> free.next()

Please tell me your problems

>>> free.send('I feel bad')

Don't be so negative

>>> free.send("Why I shouldn't ?")

Don't ask yourself too much questions

>>> free.send("ok then i should find what is good for me")

A that's good, go on

Coroutines

Native Support Language

Io (http://iolanguage.com)

Or

Lua (http://www.lua.org)

Coroutines in Python

• 원래는 없음

• Stackless Python 의 Continuation

• 근데 yield 가 거의 비슷함

• Multitask 모듈로 구현

import multitask

import time

def coroutine_1():

for i in range(3):

print 'c1'

yield i

def coroutine_2():

for i in range(3):

print 'c2'

yield i

>>> multitask.add(coroutine_1())

>>> multitask.add(coroutine_2())

>>> multitask.run()

c1

c2

c1

c2

c1

c2

아 진짜 근데 못 쓰겠어

파이스닉

감사합니다

top related