1급함수

In [12]:
fn1=lambda x,y : x+y
In [13]:
fn1(1,2)
Out[13]:
3
In [14]:
fn2=lambda x,y : x+y+10
In [15]:
fn2(1,2)
Out[15]:
13
In [16]:
base=10
fn3= lambda x,y : x+y+base
In [17]:
fn3(1,2)
Out[17]:
13
In [18]:
def mysum1():
    fn=lambda x,y : x+y
    return fn
myfn=mysum1()
myfn(1,2)
Out[18]:
3
In [19]:
mysum1()(2,5)
Out[19]:
7
In [20]:
(lambda x,y: x+y)(1,2)
Out[20]:
3

예시

In [21]:
def base_10(fn):
    def wrap(x,y):
        return fn(x,y)+10
    return wrap

def mysum(x,y):
    return x+y

mywrap=base_10(mysum)
In [22]:
mywrap(1,2)
Out[22]:
13
In [23]:
def mymultiply(x,y):
    return x*y

mywrap=base_10(mymultiply)
mywrap(10,20)
Out[23]:
210

장식자 문법 적용

In [25]:
def base_10(fn):
    def wrap(x,y):
        return fn(x,y)+10
    return wrap

@base_10
def mysum(x,y):
    return x+y
In [26]:
mysum(1,20)
Out[26]:
31
In [27]:
@base_10
def mymultiply(x,y):
    return x*y
In [28]:
mymultiply(10,20)
Out[28]:
210

memorize

In [29]:
import time

cached1={}
cached2={}

def mylongtimesum(x,y):
    key=(x,y)
    if key not in cached1:
        time.sleep(1)
        cached1[key]=x+y+10
    return cached1[key]

def mylongtimemultiply(x,y):
    key=(x,y)
    if key not in cached2:
        time.sleep(1)
        cached2[key]=(x*y)+10
    return cached2[key]
In [30]:
print(mylongtimesum(1,2))
print(mylongtimesum(1,2))
print(mylongtimesum(1,2))
print(mylongtimesum(1,2))
print(mylongtimesum(1,2))
print(mylongtimesum(1,2))
13
13
13
13
13
13
In [31]:
print(mylongtimemultiply(1,2))
12
In [32]:
print(mylongtimemultiply(1,2))
print(mylongtimemultiply(1,2))
print(mylongtimemultiply(1,2))
print(mylongtimemultiply(1,2))
12
12
12
12

장식자 사용 memoize

In [33]:
import time
In [34]:
def memoize(fn):
    cached={}
    def wrap(x,y):
        key=(x,y)
        if key not in cached:
            cached[key]=fn(x,y)
        return cached[key]
    return wrap

@memoize
def mylongtimesum(x,y):
    time.sleep(1)
    return x+y+10

@memoize
def mylongtimemultiply(x,y):
    time.sleep(1)
    return (x*y)+10
In [35]:
print(mylongtimesum(1,2))
print(mylongtimesum(1,2))
print(mylongtimesum(1,2))
print(mylongtimesum(1,2))
print(mylongtimesum(1,2))
print(mylongtimesum(1,2))
13
13
13
13
13
13
In [36]:
print(mylongtimemultiply(1,2))
print(mylongtimemultiply(1,2))
print(mylongtimemultiply(1,2))
print(mylongtimemultiply(1,2))
print(mylongtimemultiply(1,2))
print(mylongtimemultiply(1,2))
12
12
12
12
12
12
In [37]:
print(mylongtimemultiply(1,2))
12

위에서 다른 함수에 대한 cached는 다르게 적용되는 것 같음. 같은 함수에 대해서는 같은 cached적용

인자를 받는 장식자

In [40]:
def base(base_i):
    def outer(fn):
        def wrap(x,y):
            return fn(x,y)+base_i
        return wrap
    return outer
In [41]:
base_10=base(10)

@base_10
def mysum(x,y):
    return x+y

print(mysum(1,2))
print(mysum(1,3))
13
14
In [42]:
@base(30)
def mysum(x,y):
    return x+y

print(mysum(1,2))
print(mysum(1,3))
33
34
In [ ]: