# 《Python基础教程》学习笔记 Chp6 抽象

1.创建函数

>>> import math
>>> x = 1
>>> y = math.sqrt
>>> callable(x)
False
>>> callable(y)
True

>>> def hello(name) :
...     return 'hello, ' + name + "!"
...
>>> print hello('world')
hello, world!
>>> print hello('Alice')
hello, Alice!

>>> def square(x) :
...     'calculates the square of the number x.'
...     return x * x

>>> square.func_doc
'calculates the square of the number x.'

Python有些函数没有return语句，或者虽有return语句但return后面没有跟任何，这些函数都不会返回值。例：

>>> def test():
...     print 'This is printed !'
...     return
...     print 'This is not !'
...
>>> x = test()
This is printed !
>>> x
>>> print x
None

2.参数魔法

>>> storage ={}
>>> storage['first'] = {}
>>> storage['middle'] ={}
>>> storage['last'] = {}

>>> me = {'Nagnus Lie Hetland'}
>>> storage['first']['Nagnus'] = me
>>> storage['middle']['Lie'] = me
>>> storage['last']['Hetland'] = me

>>> storage['middle']['Lie']
set(['Nagnus Lie Hetland'])

>>> def init(data) :
...     data['first'] = {}
...     data['middle'] = {}
...     data['last'] = {}

>>> def lookup(data, lable, name) :
...     return data[lable].get(name)
...
>>> lookup(storage, 'middle', 'Lie')
set(['Nagnus Lie Hetland'])

>>> def store(data, full_name) :
...     names = full_name.split()
...     if(len(names)) == 2 : names.insert(1, '')
...     lables = ('first', 'middle', 'last')
...     for lable, name in zip(lables, names):
...         people = lookup(data, lable, name)
...         if people :
...             people.append(full_name)
...         else :
...             data[lable][name] = [full_name]
...             

>>> MyNames = {}
>>> init(MyNames)
>>> store(MyNames, 'Magus Lie Hetland')
>>> lookup(MyNames, 'middle', 'Lie')
['Magus Lie Hetland']
>>> store(MyNames, 'Robin Hood')
>>> store(MyNames, 'Robin Locksley')
>>> lookup(MyNames, 'first', 'Robin')
['Robin Hood', 'Robin Locksley']
>>> store(MyNames, 'Mr. Gumby')
>>> lookup(MyNames, 'middle', '')
['Robin Hood', 'Robin Locksley', 'Mr. Gumby']
>>> MyNames
{'middle': {'': ['Robin Hood', 'Robin Locksley', 'Mr. Gumby'], 'Lie': ['Magus Lie Hetland']}, 'last': {'Gumby': ['Mr. Gumby'], 'Locksley': ['Robin Locksley'], 'Hood': ['Robin Hood'], 'Hetland': ['Magus Lie Hetland']}, 'first': {'Magus': ['Magus Lie Hetland'], 'Mr.': ['Mr. Gumby'], 'Robin': ['Robin Hood', 'Robin Locksley']}}

>>> def hello(greeting, name):
...     print '%s, %s !' %(greeting, name)
...
>>> def hello1(name, greeting):
...     print '%s, %s !' %(name, greeting)
...
>>> hello('Hello', 'world')
Hello, world !
>>> hello1('Hello', 'world')
Hello, world !

>>> hello(greeting = 'Hello', name = 'world')
Hello, world !
>>> hello(name = 'world', greeting = 'Hello')
Hello, world !

>>> hello1(greeting = 'Hello', name = 'world')
world, Hello !

>>> def hello2(greeting = 'Hello', name = 'world'):
...     print '%s, %s !' %(greeting, name)
...
>>> hello2()
Hello, world !
>>> hello2(greeting = 'Greetings')
Greetings, world !
>>> hello2(greeting = 'Greetings', name = 'world')
Greetings, world !

>>> def hello3(name, greeting = 'Hello', punctuation = '!'):
...     print '%s %s%s' %(name, greeting, punctuation)
...
>>> hello3('Mars')
Mars Hello!
>>> hello3('Mars', 'Howdy')
Mars Howdy!
>>> hello3('Mars', 'Howdy', '...')
Mars Howdy...
>>> hello3('Mars', greeting = 'ni hao !')
Mars ni hao !!
>>> hello3()
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: hello3() takes at least 1 argument (0 given)

>>> def print_params(*params) :
...     print params
...
>>> print_params(1,2,3)
(1, 2, 3)

>>> print_params1('Params : ', 1,2,3)
Params :
(1, 2, 3)
>>> print_params1('Nothing ! ')
Nothing !
()

>>> def print_params2(**params):
...     print params
...
>>> print_params2(x=1,y=2,z=3)
{'y': 2, 'x': 1, 'z': 3}
>>> def print_params2(x, y, z=3, *paspar, **keypar):
...     print x, y, z
...     print paspar
...     print keypar
...
>>> print_params2(1,2,3,5,6,7,foo=1,bar=2)
1 2 3
(5, 6, 7)
{'foo': 1, 'bar': 2}
>>> print_params2(1,2)
1 2 3
()
{}
>>> print_params2(1,2,3,5,6,7,8,9,foo=1,bar=2,foo1=3,bar1=4)
1 2 3
(5, 6, 7, 8, 9)
{'bar1': 4, 'foo': 1, 'bar': 2, 'foo1': 3}

>>> def add(x,y):
...     return x+y
...
>>> params = (1,2)
3

>>> def hello2(greeting = 'Hello', name = 'world'):
...     print '%s, %s !' %(greeting, name)
...
>>> params = {'name': 'Sir Robin', 'greeting' : 'Well met'}
>>> hello2(**params)
Well met, Sir Robin !

>>> def story(**kwds):
...     return 'once upon a time , there was a '\
...         '%(job)s called %(name)s.' %kwds
...
>>> def power(x, y, *others):
...     if others:
...         print 'Received redundant parameters : ', others
...     return pow(x, y)
...
>>> def interval(start, stop=None,step=1):
...     'Imitates range() for step > 0'
...     if stop is None:                #如果没有为stop提供值。。。。。
...         start, stop=0, start        #指定参数（序列解包）
...     result = []
...     i = start
...     while i < stop:
...         result.append(i)
...         i+=step
...     return result
...
>>> print story(job = 'king', name = 'Gumby')
once upon a time , there was a king called Gumby.
>>> params = {'job':'language', 'name':'Pythone'}
>>> print story(**params)
once upon a time , there was a language called Pythone.
>>> del params['job']
>>> params
{'name': 'Pythone'}
>>> print story(job='stroke of genius',**params)
once upon a time , there was a stroke of genius called Pythone.
>>> params
{'name': 'Pythone'}
>>> power(2,3)
8
>>> power(y=3,x=2)
8
>>> params=(5,)*2
>>> power(*params)
3125
>>> power(3,3,'Hello , world !')
Received redundant parameters :  ('Hello , world !',)
27
>>> interval(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> interval(1,5)
[1, 2, 3, 4]
>>> interval(3,12,4)
[3, 7, 11]
>>> power(*interval(3,7))
Received redundant parameters :  (5, 6)
81

3.作用域

>>> def combine(parameter):
...     print parameter + globals()['parameter']
...
>>> parameter = 'berry'
>>> combine('shrub')
shrubberry

Python的函数是可以嵌套的，也就是说可以将一个函数放在另一个里面。例：

>>> def foo():
...     def bar():
...         print 'hello , world !'
...     bar()
...
>>> foo()
hello , world !

>>> def multiplier(factor):
...     print factor
...     def multiplyByFactor(number):
...         print 'number is : ', number, ' , factor is : ', factor
...         return number * factor
...     return multiplyByFactor
...
>>> double = multiplier(2)
2
>>> double(5)
number is :  5  , factor is :  2
10
>>> multiplier(5)(4)
5
number is :  4  , factor is :  5
20

>>> def factorial(n):
...     if n == 1:
...         return 1
...     return n * factorial(n-1)
...
>>> factorial(5)
120
>>> factorial(1)
1

>>> def power(x, n):
...     if n==0:
...         return 1
...     return x * power(x, n-1)
...
>>> power(3,5)
243
>>> power(3,0)
1

>>> def search(sequence, number, lower = 0, upper = None):
...     if upper is None : upper = len(sequence) - 1
...     if lower == upper :
...         print 'sequence[upper] is : ', sequence[upper]
...         assert number == sequence[upper]
...         return upper
...     else :
...         middle = (lower + upper) / 2
...         print 'middle is : ', middle, ' ; sequence[middle] is : ', sequence[middle]
...         if number > sequence[middle] :
...             return search(sequence, number, middle + 1, upper)
...         else :
...             return search(sequence, number, lower, middle)
...
>>> sequence = [34,67,8,123,4,100,95]
>>> sequence.sort()
>>> sequence
[4, 8, 34, 67, 95, 100, 123]
>>> search(sequence, 34)
middle is :  3  ; sequence[middle] is :  67
middle is :  1  ; sequence[middle] is :  8
middle is :  2  ; sequence[middle] is :  34
sequence[upper] is :  34
2
>>> search(sequence, 95)
middle is :  3  ; sequence[middle] is :  67
middle is :  5  ; sequence[middle] is :  100
middle is :  4  ; sequence[middle] is :  95
sequence[upper] is :  95
4

map
map函数可以将序列中的元素全部传递给一个函数。例：

>>> map(str, range(10))
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

filter
filter函数可以基于一个返回布尔值的函数对元素进行过滤。例：

>>> def func(x):
...     return x.isalnum()
...
>>> seq = ['faa', 'fafe', '###', '***']
>>> filter(func, seq)
['faa', 'fafe']

reduce
reduce函数会将序列的前两个元素与给定的函数联合使用，并且将它们的返回值和第三个元素继续联合使用，知道整个序列处理完毕，并且得到一个最终结果。

>>> nums = [1,2,3,4,5]
...
>>> reduce(lambda x, y : x + y, nums)
15

4.本章新函数
map（func，seq[, seq, …]） 对序列中的每个元素应用函数
filter（func, seq） 返回其函数为真的元素的列表
reduce（func, seq[, initial]） 等同于func（func（func（seq[0], seq[1], seq[2], …）））
sum(seq) 返回seq中所有元素的和
apply（func[，args[, kwargs]]） 调用函数，可以提供参数

• 本文已收录于以下专栏：

## python基础教程_学习笔记12：充电时刻——模块

• signjing
• 2014年06月20日 16:17
• 1336

## 《Python基础教程》学习笔记（6-7抽象）

6. 抽象6.1 函数使用def定义函数def fibs(num): result = [0, 1] for i in range(num - 2): result.a...
• u013980127
• 2016年10月30日 21:38
• 178

## 《Python基础教程》第6~8章 学习笔记

《Python基础教程》 学习笔记 第二弹，6-8章。markdown排版。
• hcbbt
• 2014年01月26日 17:44
• 2281

## python基础教程_学习笔记9：抽象

• signjing
• 2014年06月14日 15:11
• 1283

## Python基础教程第六章学习笔记——抽象

6 抽象 介绍如何将语句组织成函数，告诉计算机如何做事（只告诉一次就可以） 还会介绍参数（parameter）和作用域（scope）概念 递归的概念及在程序中的用途 6.1 懒惰即美德 一段代码可能要...
• youngersteral
• 2017年09月14日 12:56
• 175

## 《Python基础教程》学习笔记（10-11模块和文件）

10. 模块相关Python的标准安装包包括一组模块，称为标准库（standard library）。10.1 模块10.1.1 模块是程序# hello.py print "Hello, world...
• u013980127
• 2017年03月12日 14:48
• 400

## Python学习笔记【六】——《python基础教程》:: 抽象

• heli200482128
• 2017年07月06日 10:56
• 153

## <<Python基础教程>>学习笔记 | 第06章 | 抽象

• Jerry_1126
• 2014年09月22日 21:29
• 1387

## Python基础教程第七章学习笔记——更加抽象

7 更加抽象—创建自己的对象 前面讲了： Python主要的内建对象类型（数字、字符串、列表、元组和字典） 内建函数和标准库的用法 自定义函数的方式 本章主讲： 创建自己的对象（尤其是类型或者被称为类...
• youngersteral
• 2017年09月18日 20:38
• 153

## 《Python基础教程》学习笔记 Chp7 更加抽象

• lzh398651363
• 2016年06月01日 17:40
• 195

举报原因： 您举报文章：《Python基础教程》学习笔记 Chp6 抽象 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)