Python: 《Python基础教程》 读书笔记 第六章 抽象 函数 参数

6.1创建函数

>>> x=1

>>> y=math.sqrt

>>> callable(x)

False

>>> callable(y)

True

deffib(num):

result=[0,1]

fori inrange(num-2):

result.append(result[-2]+result[-1])

returnresult

6.1.1记录函数

>>> def square(x):

‘calculates the square of the number x’

return x*x

>>> square.__doc__

‘calculates the square of the number x’

>>> help(square)

Help on function square:

square(x)

calculates thesquare of the number x

6.2.1参数

>>> def try_to_change(n):

n=’Mr.gumby’

>>> name=’Mrs.entity’

>>> try_to_change(name)

>>> name

‘Mrs.entity’

>>> def hello(greeting=’hello’,name=’world’):

print ‘%s,%s!’%(greeting,name)

>>> hello()

hello,world!

>>> hello(‘greeting’)

greeting,world!

>>> hello(‘greeting’,’universe’)

greeting,universe!

6.2.2收集参数：

>>> def print_params(*params):

print params

>>> print_params(‘testing’)

(‘testing’,)

>>> print_params(1,2,3)

(1, 2, 3)

>>> defprint_params_2(title,*params):

print title

print params

>>>print_params_2(‘params:’,1,2,3)

params:

(1, 2, 3)

>>> print_params_2(‘nothing:’)

nothing:

()

>>>print_params_2(‘hmm…’,something=42)

Traceback (most recent call last):

File “>”, line 1, in

TypeError: print_params_2() got anunexpected keyword argument ‘something’

>>> def print_params_3(**params):

… print params

>>> print_params_3(x=1,y=2,z=3)

{‘y’: 2, ‘x’: 1, ‘z’: 3}#返回的是字典而不是元组

>>> defprint_params_4(x,y,z=3,*pospar,**keypar):

… print x,y,z

… print pospar

… print keypar

>>>print_params_4(1,2,3,5,6,7,foo=1,bar=2)

1 2 3

(5, 6, 7)

{‘foo’: 1, ‘bar’: 2}

>>> print_params_4(1,2)

1 2 3

()

{}

>>> def init(data):

data[‘first’]={}

data[‘middle’]={}

data[‘last’]={}

def lookup(data,label,name):

return data[label].get(name)

def store(data,*full_names):

for full_name in full_names:

names=full_name.split()

if len(names)==2:names.insert(1,”)

labels=’first’,’middle’,’last’

for label,name in zip(labels,names):

people=lookup(data,label,name)

if people:

people.append(full_name)

else:

data[label][name]=[full_name]

>>> store(d,’luke skywalker’,’anakin skywalker’)

>>> lookup(d,’last’,’skywalker’)

[‘luke skywalker’, ‘anak in skywalker’]

6.2.3 反转过程

>>> def add(x,y):return x+y

>>> params=(1,2)

3

>>> defhello_3(greeting=’Hello’,name=’world’):

… print ‘%s,%s!’%(greeting,name)

>>> params={‘name’:’sirrobin’,’greeting’:’well met’}

>>> hello_3(**params)

well met,sir robin!

6.3作用域

>>> def foo():

… x=42

>>> x=1

>>> foo()

>>> x

1

>>> def combine(parameter):printparameter+external

>>> external=’berry’

>>> combine(‘shrub’)

shrubberry

6.4.1两个经典:阶乘和幂

>>> def factorial(n):

… result=n

… for i in range(1,n):

… result*=i

… return result

>>> factorial(5)

120

>>> def factorial(n):

… if n==1:

… return 1

… else:

… return n*factorial(n-1)

>>> factorial(5)

120

>>> def power(x,n):

… result=1

… for i in range(n):

… result*=x

… return result

>>> power(2,3)

8

>>> def power(x,n):

… if n==0:

… return 1

… else:

… return x*power(x,n-1)

>>> power(2,3)

8

map(func,seq[,seq,…])：对序列中的每个元素应用函数

filter(func .seq)：返回其函数为真的元素的列表

reduce(func,seq[,initial])：等同于func(func(func(seq[0],seq[1]),…)

sum(seq)：返回seq中所有元素的和

apply(func[,args[,kwargs]])：调用函数，可以提供参数

Sidebar