您的位置:首页 > 编程语言 > Python开发

python 教程 第五章、 函数

2011-10-13 11:19 246 查看
第五章、 函数
定义语句后面要加冒号
1) 定义函数

def sayHello():

print 'Hello World!'

sayHello()

2) 变量作用域
LEGB原则
L本地作用域
E上层结构中def或lambda的作用域
G全局作用域
B内置作用域

3) 工厂/闭合函数

def maker(N):

def action(X):

return X ** N

return action


f = maker(2)

print f    #<function action at 0x00E87730>

print f(3) #9

print f(4) #16

g = maker(3)

print g(3) #27

4) 函数形参

def printMax(a, b):

if a > b:

print a, 'is maximum'

else:

print b, 'is maximum'

printMax(3, 4)

5) 局部变量
x是函数的局部变量

def func(x):

print 'x is', x

x = 2

print 'Changed local x to', x

x = 50

func(x)

print 'x is still', x

全局变量

def func():

global x

print 'x is', x

x = 2

print 'Changed local x to', x

x = 50

func()

print 'Value of x is', x

6) 默认参数值

def say(message, times = 1):

print message * times

say('Hello')

7) 关键参数

def func(a, b=5, c=10):

print 'a is', a, 'and b is', b, 'and c is', c

func(3)

8) 可变长度参数
*非关键字可变长参数(元组)

>>>def tupleVarArgs(arg1, arg2 = "defaultB", *theRest):

print 'arg 1:', arg1

print 'arg 2:', arg2

for eachXtrArg in theRest:

print 'another arg:', eachXtrArg

>>>tupleVarArgs('abc')

arg 1: abc

arg 2: defaultB

>>>tupleVarArgs(23, 4.56)

arg 1: 23

arg 2: 4.56

>>>tupleVarArgs('abc', 123, 'xyz', 456.7)

arg 1: abc

arg 2: 123

another arg: xyz

another arg: 456.7

**关键字变量参数(字典)

>>>def dictVarArgs(arg1, arg2 = "defaultB", **theRest):

print 'arg 1:', arg1

print 'arg 2:', arg2

for eachXtrArg in theRest.keys():

print 'Xtra arg %s: %s' \

%(eachXtrArg, str(theRest[eachXtrArg]))

>>>dictVarArgs(1220, 740.0, c = 'gmail')

arg 1: 1220

arg 2: 740.0

Xtra arg c: gmail

>>>dictVarArgs(arg2 = 'tales', c = 123, d = 'poe', arg1 = 'my')

arg 1: my

arg 2: tales

Xtra arg c: 123

Xtra arg d: poe

>>>dictVarArgs('one', d = 10, e = 'zoo', men = ('freud', 'gaudi'))

arg 1: one

arg 2: defaultB

Xtra arg men: ('freud', 'gaudi')

Xtra arg e: zoo

Xtra arg d: 10

组合使用

>>>def newfoo(arg1, arg2, *nkw, **kw):

print 'arg1 is :', arg1

print 'arg2 is :', arg2

for eachNKW in nkw:

print 'add non-keyword:', eachNKW

for eachKW in kw.keys():

print "add keyword '%s': %s" %(eachKW, kw[eachKW])

>>>newfoo(10, 20, 30, 40, foo = 50, bar = 60)

arg1 is : 10

arg2 is : 20

add non-keyword: 30

add non-keyword: 40

add keyword 'foo': 50

add keyword 'bar': 60

>>>newfoo(2, 4, *(6, 8), **{'foo':10, 'bar':12})

arg1 is : 2

arg2 is : 4

add non-keyword: 6

add non-keyword: 8

add keyword 'foo': 10

add keyword 'bar': 12

>>>aTuple = (6, 7, 8)

>>>aDict = {'z':9}

>>>newfoo(1, 2, 3, x = 4, y = 5, *aTuple, **aDict)

arg1 is : 1

arg2 is : 2

add non-keyword: 3

add non-keyword: 6

add non-keyword: 7

add non-keyword: 8

add keyword 'y': 5

add keyword 'x': 4

add keyword 'z': 9

>>>

9) return语句

def maximum(x, y):

if x > y:

return x

else:

return y

print maximum(2, 3)

10) DocStrings
文档字符串,一个多行字符串。
你可以使用__doc__(注意双下划线)调用函数的文档字符串属性。
建议对你所写的任何正式函数编写文档字符串。

def printMax(x, y):

'''Prints the maximum of two numbers.


The two values must be integers.'''

x = int(x) # convert to integers, if possible

y = int(y)

if x > y:

print x, 'is maximum'

else:

print y, 'is maximum'


printMax(3, 5)

print printMax.__doc__

11) lambda匿名函数
使用方法:lambda [arg1[,arg2,arg3,...,argn]] : expression

Factorial = lambda x: x > 1 and x * Factorial(x - 1) or 1

print Factorial(6)

max = lambda a, b: (a > b) and a or b

print max(2,3)

x, y = 11, 12

print (lambda : x+y)() #23

print (lambda x: x+y)(x) #23

print (lambda x: x+y)(y) #24

12) Generator生成器
可以保存状态的函数,用yield指令(不是return)返回一个值,并保存当前整个函数执行状态,等待下一次调用,如此循环往复,直至函数末尾,发生StopIteration异常。
generator利用next()来获取下一个返回值。

def gen(n):

for i in xrange(n):

yield i

g = gen(5)

print g #<generator object gen at 0x00E82350>

print g.next() #0

print g.next() #1

for x in g:

print x    #2, 3, 4

print g.next() #Error: StopIteration

13) Iterations迭代器
Iteration: iter and next

L = [1, 2, 3]

I = iter(L)

print I.next() #1

print I.next() #2

print I.next() #3

print I.next() #StopIteration Error

for x in I: print(x) # map iterator is now empty: one pass only


Y = iter(L)

while True:

try:

X = next(Y)  # Or call I.__next__

except StopIteration:

break

print X ** 2 #1 4 9

支持两个(2.6支持map, zip, range, 3.0只有range支持)

R = range(3)

I1, I2 = iter(R), iter(R)

print next(I1), next(I1), next(I2) #0 1 0

14) 内建函数
enumerate函数
获得数组,或列表的索引及值

string = 'hi'

print list(enumerate(string)) #[(0, 'h'), (1, 'i')]

for index,value in enumerate(string):

print index, value

#0 h

#1 i

filter函数
filter(bool_func,seq):此函数的功能相当于过滤器。调用一个布尔函数bool_func来迭代遍历每个seq中的元素;返回一个使bool_seq返回值为true的元素的序列。

def f(x): return x % 2 != 0 and x % 3 != 0

print filter(f, range(2, 25))

map函数
map(func,seq1[,seq2...]):将函数func作用于给定序列的每个元素,并用一个列表来提供返回值;如果func为None,func表现为身份函数,返回一个含有每个序列中元素集合的n个元组的列表。

def cube(x): return x*x*x

print map(cube, range(1, 5)) #[1, 8, 27, 64]

print filter(cube, range(1,5)) #[1, 2, 3, 4]

print map(lambda x : x * 2,[1,2,3,4,[5,6,7]])

#运行结果
[2, 4, 6, 8, [5, 6, 7, 5, 6, 7]]
None参数

>>>map(None, 'abc', 'xyz123')

[('a', 'x'), ('b', 'y'), ('c', 'z'), (None, '1'), (None, '2'), (None, '3')]

reduce函数
reduce(func,seq[,init]):func 为二元函数,将func作用于seq序列的元素,每次携带一对(先前的结果以及下一个序列的元素),连续的将现有的结果和下一个值作用在获得的随后的结果上,最后减少我们的序列为一个单一的返回值:如果初始值init给定,第一个比较会是init和第一个序列元素而不是序列的头两个元素。

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

print reduce((lambda x, y: x * y), [1, 2, 3, 4]) #24

zip函数
zip允许用户使用for循环访问平行的多个序列,zip将一个或多个序列作为参数,然后返回一系列的与序列中项平行的元组.

x, y = [1, 2, 3], [4, 5, 6]

print zip(x, y) #[(1, 4), (2, 5), (3, 6)]

print list(zip(x, y)) #[(1, 4), (2, 5), (3, 6)]

print dict(zip(x, y)) #{1: 4, 2: 5, 3: 6}

print tuple(zip(x, y)) #((1, 4), (2, 5), (3, 6))


T1, T2, T3 = (1,2,3), (4,5,6), (7,8,9)

print list(zip(T1, T2, T3)) #[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

print tuple(zip(T1, T2, T3)) #((1, 4, 7), (2, 5, 8), (3, 6, 9))

其他函数
type得到对象的类型

>>>type(42) #<type 'int'>

>>>type(type(42)) #<type 'type'>

>>>type([].append) #<type 'builtin_function_or_method'>

cmp比较两个对象是否相等

>>>cmp(1,2) #-1

>>>cmp(0xFF, 255) #0

类型转换

>>>float(4) #4.0

>>>complex(2.4, 8) #(2.4+8j)

>>>coerce(1j, 123) #(1j, (123+0j))

ASCII转换

>>>ord('s') #115返回对应的ASCII码

>>>chr(115)# 's'返回对应的字符

进行转换

>>>hex(255) #'0xff'

>>>oct(255) #'0377' 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: