不一样的Python(7)——函数

来源:互联网 发布:网络教育要交几年学费 编辑:程序博客网 时间:2024/06/06 00:53
1. 参数是以传引用的方式;
def fun1(l):  for i in range(len(l)):    l[i] *= 2def fun2(l):  l = l + l

如果以一个类型为list的L为参数调用fun1,返回时L的内容会发生改变;但同样以一个类型为list的L为参数调用fun2,返回时L的内容不会发生改变。

2. 函数体内的对某变量的第一次赋值,都会创建一个新的局部变量;

X = 100def func():  X = 50

如果接下来调用函数func,调用结束之后X的值仍然是100。在函数体内X=50是对一个新创建的局部变量赋值。如果想在函数体内修改函数体外的X,需要用到global关键字:

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

但是,如果只是读取函数体外的全局变量的值,不需要用到global关键字:

globvar = 0def set_globvar_to_one():    global globvar    # Needed to modify global copy of globvar    globvar = 1def print_globvar():    print globvar     # No need for global declaration to read value of globvarset_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 actionf = 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 actionf = 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, cf(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 resultprint f(1, 2, 3, 4)

上述打印出10。

def f(**args):  result = 0  for x in args:    result += args[x]  return resultprint f(a=1, b=2, c=3, d=4)

上述代码打印出10。

8. yield函数生成器

def buildsquare(n):  for x in range(n):    yield x ** 2L = [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 Lfunc()func()func()

上述代码中,三次调用func打印的结构互不相同,分写是[1]、[1, 1]和[1, 1, 1]。

更多资料,可参考http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument和http://effbot.org/zone/default-values.htm。

 

10. 函数的decorator:

# The decorator to make it bolddef 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 italicdef makeitalic(fn):    # The new function the decorator returns    def wrapper():        # Insertion of some code before and after        return "<i>" + fn() + "</i>"    return wrapper@makebold@makeitalicdef 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。