網頁

2015年6月28日 星期日

[Python] inspect.getargspec

主題: inspect.getargspec

Example:

#!/usr/bin/python

import inspect

def myfunc(a, b=2, c=1, *args, **kwargs):
        print ("%r %r %r" % (a,b,c))
        return a

argspec = inspect.getargspec(myfunc)

print (str(argspec))

結果:

ArgSpec(args=['a', 'b', 'c'], varargs='args', keywords='kwargs', defaults=(2, 1))

結論:

利用inspect.getargspec可以取得func的argument的相關資訊

[Python] bind

主題:想要對Python的function有bind的能力


簡介:

C++, javascript裡面都叫bind但在python則由functools的partial完成。

什麼是bind ?
就是"綁定", 綁定什麼 ? 讓你的func參數的parameter綁定某些值。

相信看完下面的範例就會有感覺

Example:

#!/usr/bin/python3

from functools import partial

def myfunc(x, y, z):
        print ("%r %r %r" % (x,y,z))

binded_myfunc = partial(myfunc, 2, 3, 4)

myfunc(1,2,3)

binded_myfunc()

結果:
1 2 3
2 3 4


[blog] code highlight

主題: 如何在google blog內貼code可以highlight ?


Ref: 主要還是要看這一篇 非常詳細。
簡述一下:
Step1: 在template內head前貼上javascript code
Step2: use it !
舉例來說如果是python code
<pre class="brush:python;">
...
</pre>

舉例來說如果是php code
<pre class="brush:php;">
...
</pre>

效果:
#!/usr/bin/python3

print ("This is python code")


2015年6月25日 星期四

[Python][Metaprogramming] 9.1 decorator

介紹@wraps decorator


沒加@wraps

<pre class='codeblock'>#!/usr/bin/python

import time
from functools import wraps

def timethis(func):
 '''
 Decorator that reports the excution time
 '''
 #@wraps(func)
 def wrapper(*args, **kwargs):
  start = time.time()
  result = func(*args, **kwargs)
  end = time.time()
  print(func.__name__, end-start)
  return result
 return wrapper

@timethis
def countdown(n):
 '''
 Counts down
 '''
 while n > 0:
  n -= 1


countdown(10000)
print countdown.__name__
print countdown.__doc__

<\pre>

結果:

'countdown', 0.00028896331787109375) 
wrapper
None

有加@wraps

結果:

('countdown', 0.00029587745666503906) 
countdown 
Counts down

結論:

寫decorator若想保留原來的funcion __name__, __doc__那就要加 @wraps
否則就會被替換成 wrapper, None