不一樣的Python(7)——函數

1. 參數是以傳引用的方式;
def fun1(l):
  for i in range(len(l)):
    l[i] *= 2

def fun2(l):
  l = l + l

如果以一個類型爲list的L爲參數調用fun1,返回時L的內容會發生改變;但同樣以一個類型爲list的L爲參數調用fun2,返回時L的內容不會發生改變。

2. 函數體內的對某變量的第一次賦值,都會創建一個新的局部變量;

X = 100

def func():
  X = 50

如果接下來調用函數func,調用結束之後X的值仍然是100。在函數體內X=50是對一個新創建的局部變量賦值。如果想在函數體內修改函數體外的X,需要用到global關鍵字:

X = 100
def func():
  global X
  X = 50

但是,如果只是讀取函數體外的全局變量的值,不需要用到global關鍵字:

globvar = 0

def set_globvar_to_one():
    global globvar    # Needed to modify global copy of globvar
    globvar = 1

def print_globvar():
    print globvar     # No need for global declaration to read value of globvar

set_globvar_to_one()
print_globvar()       # Prints 1

更多討論,詳見:http://stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them

3. 函數可以嵌套

def maker(n):
  def maker(x):
    return x ** n
  return action

f = maker(2)
print f(3)
print f(4)

4. lambda表達式。下面代碼中的“x=x”是參數的缺省值,表示在lambda表達式中的參數x的缺省值是func中的x。

def func():
  x = 4
  action = (lambda n, x=x: x **n)
  return action

f = func()
print f(3)
print f(3, 2)

lambda體內只能由一個表達式,不能有語句(如if、for、while)等。

lambda經常與map, filter, reduce等函數一起使用。比如

counters = [1, 2, 3, 4]
list(map((lambda x: x + 3), counters))

結果爲[4, 5, 6, 7]

list(filter((lambda x: x > 0), range(−5, 5)))

結果爲[1, 2, 3, 4]

 

reduce((lambda x, y: x + y), [1, 2, 3, 4])

結果爲10
 

5. 函數也是一個實例對象,也有屬性(attribute)。

def tester(start):
  def nested(label):
    print label, nested.state
    nested.state += 1
  nested.state = start
  return nested

 6. 函數參數及其調用方式:

def f(a, b, c):
  print a, b, c

f(c=3, b=2, a=1)
args = (1, 2, 3)
f(*args)
args = {'a':1, 'b':2, 'c':2}
f(**args)

上述代碼打印的結果是三行1, 2, 3

7. 在定義函數的時候,*和**表示數目可變的參數,分別把參數當成tuple和dictionary

def f(*args):
  result = 0
  for x in args:
    result += x
  return result

print f(1, 2, 3, 4)

上述打印出10。

def f(**args):
  result = 0
  for x in args:
    result += args[x]
  return result

print f(a=1, b=2, c=3, d=4)

上述代碼打印出10。

8. yield函數生成器

def buildsquare(n):
  for x in range(n):
    yield x ** 2

L = [x for x in buildsquare(5)]

運行上述代碼,L中包括[0, 1, 4, 9, 16]

Generators are used only once. 比如下面的代碼中:

squaredNumbers = buildsquares(5)
[x for x in squareNumbers] # [0, 1, 4, 9, 16]
[x for x in squareNumbers] # []

如果想再次使用squareNumbers,必須再次調用squareNumbers = buildsquares(5)
下列網頁討論爲什麼C#中需要yield,可供參考:http://stackoverflow.com/questions/14057788/why-use-the-yield-keyword-when-i-could-just-use-an-ordinary-ienumerable?newsletter=1&nlcode=59133%7c9706

9. 函數的缺省值可能會變化

def func(L = []):
  L.append(1)
  print L

func()
func()
func()

上述代碼中,三次調用func打印的結構互不相同,分寫是[1]、[1, 1]和[1, 1, 1]。

更多資料,可參考http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argumenthttp://effbot.org/zone/default-values.htm

 

10. 函數的decorator:

# The decorator to make it bold
def makebold(fn):
    # The new function the decorator returns
    def wrapper():
        # Insertion of some code before and after
        return "<b>" + fn() + "</b>"
    return wrapper

# The decorator to make it italic
def makeitalic(fn):
    # The new function the decorator returns
    def wrapper():
        # Insertion of some code before and after
        return "<i>" + fn() + "</i>"
    return wrapper

@makebold
@makeitalic
def say():
    return "hello"

print say() 
#outputs: <b><i>hello</i></b>

上述代碼和下面的代碼等價

def say():
    return "hello"
say = makebold(makeitalic(say))

print say() 
#outputs: <b><i>hello</i></b>


詳細討論,可參考http://stackoverflow.com/questions/739654/understanding-python-decorators?newsletter=1&nlcode=59133|9706

發佈了35 篇原創文章 · 獲贊 7 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章