不一样的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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值