Core Python Programming

内容概要: 函数装饰器, 函数的参数, lambda表达式, 内建函数filer()和map(), 函数模板, 变量作用域, 列表解析, 生成器表达式

函数式编程

1. 函数的装饰器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from time import ctime,sleep
def tsfunc(func):
def wrapperFunc():
print("[%s] :---> %s()"%(ctime(),func.__name__))
return func()
print("in function tsfunc : func="+func.__name__)
return wrapperFunc

@tsfunc
def foo():
pass

def goo():
pass

foo()
sleep(2)
#装饰器的效果其实就如同下面的函数
tsfunc(goo)()

2.默认参数和可变长参数

1
2
3
4
5
6
7
8
9
10
11
def foo(a,arg="Wordl",*rest):
print("arg1 = "+a)
print("arg2 = "+arg)
for ag in rest:
print("another arg = "+ag)

foo("Hello")
foo("Hello","CHina")
foo("cool",arg="down")
foo("Hello","CC","1","2","3")
foo("hi",arg="go")

3. 关键字变量参数: dict

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 函数定义
def goo(arg1,arg2="default_2",*tups,**dicts):
print("formal arg = "+arg1)
print("formal arg = "+arg2)
for var in tups:
print("a tuple arg = "+str(var))
for ar in dicts.keys():
print("a dict arg: %s = %s"%(str(ar),str(dicts[ar])))

#函数调用示例
goo("1")

goo("1","2")

goo("22",arg2="1",c=12,d=123,e=34)

goo("22","1","tup1",c=12,d=123,e=34)

goo("22","1","tup1","tup2",c=12,d=123,e=34)

goo("22","1",*("tup1","tp2"),**{"c":12,"d":123,"e":34})

goo("22","1",4,5,*("tup1","tp2"),**{"c":12,"d":123,"e":34})

goo("22","1",4,5,*("tup1","tp2"),a=1,b=2,**{"c":12,"d":123,"e":34})

4. 匿名函数和lambda: python允许使用lambda关键字创造匿名函数

lambda [arg1,arg2…]: expression

1
2
3
tr = lambda : True

tr()
1
2
3
4
5
add = lambda x,y=1: x+y


add(1)
add(1,4)
1
2
3
4
5
ret = lambda *x : x

ret(1,2,3,4)

ret(3)

5. 内建函数: filter(), map(), reduce()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# odd = lambda n: n%2

def odd(n):
return n%2

nums = [3,5,6,8,89]

# filter返回为True的
for i in filter (odd, [2,3,5,6,7,9,10]):
print(i)

#map()
a = map(lambda x:x**2, [1,2,3,4,5,6,7])
for i in a:
print(i)

b = map(lambda x,y:(x+y,x-y),[1,3,5],[2,4,6])
for i in b:
print(i)


### reduce()

# reduce((lambda x,y:x+y),range(5))

6. partial function application : 函数模板

1
2
3
4
5
6
7
8
9
10
from functools import partial

def add(x,y):
return x-y

add1=partial(add,1)
add1(2)

add2=partial(add,y=1)
add2(2)

7. 变量作用域

1
2
3
4
5
6
7
8
9
bar = 1
def foo():
bar = 200
print("In function foo, bar=%d"%bar)

#
print("In __main__, bar=%d"%bar)
foo()
print("After foo(), in __main__, bar=%d"%bar)
1
2
3
4
5
6
7
8
9
10
bar = 1
def foo():
global bar
bar = 200
print("In function foo, bar=%d"%bar)

#
print("In __main__, bar=%d"%bar)
foo()
print("After foo(), in __main__, bar=%d"%bar)

8. closure闭包

1
2
3
4
5
6
7
8
9
10
11
12
13
def foo(start=0):
count = [start]
def goo():
count[0]+=1
return count[0]
return goo

c = foo(1)
print(c)
print(c())
print(c())
print(c())
print(c())

9. lambda表达式及其作用域

1
2
3
4
5
6
7
8
9
x = 10
def foo():
y = 5
bar = lambda :x+y
print(bar())
y=8
print(bar())

foo()
1
2
3
4
5
6
7
8
9
x = 10
def foo():
y = 5
bar = lambda y=y:x+y
print(bar())
y=8
print(bar())

foo()
1
2
3
4
5
6
7
8
9
x = 10
def foo():
y = 5
bar = lambda z:x+z
print(bar(y))
y=8
print(bar(y))

foo()

10, 列表解析

[expression for iter_var in iterable]

1
2
3
a = map(lambda x:x**2, range(5))
for i in a:
print("%d"%i,end="\t")
1
[x**2 for x in range(5)]

[expression for iter_var in iterable if cond_expression]

1
[x for x in [11,2,23,22,8,10,5,17] if x%2]

11. 生成器表达式

(expression for iter_var in iterable if cond_expression)

生成器表达式是列表解析的一个扩展

  • 列表解析的一个不足就是必须生成所有数据,用以创建整个列表。这可能对有大量数据的iterator有负面效应
  • 生成器表达式与列表解析的语法几乎一样,不过它不返回列表,而是返回一个生成器,它在内存上更有效率
1
2
3
4
5
6
7
longest = max(len(x.strip()) for x in open('his.csv'))

l = max([len(x.strip()) for x in open("his.csv")])

longest = max((len(x.strip()) for x in open('TestDecorator.ipynb')))

l = max([len(x.strip()) for x in open("TestDecorator.ipynb")])