python 第6章抽象
1.callable(函数) 能不能被调用
2.记录函数
def fibs(num): 'This is just doc for document!' fb = [0,1] for i in range(num-2): fb.append(fb[-1]+fb[-2]) return fb print fibs(5) print fibs.__doc__
>>>
[0, 1, 1, 2, 3]
This is just doc for document!
>>>
3.传参问题
python 中函数传入对象就可以在函数中改变实际值
class node: num = 0 num=node() change(num) print num.num print num5
<__main__.node instance at 0x02B48760>
4.默认参数
def manners(say = "Hi",name='john'): 'This is just doc for document!' print say+"."+name manners() manners("fun") manners(name = "fun")>>>
Hi.john
fun.john
Hi.fun
>>>
5.收集参数
# -*- coding: cp936 -*- def collect(*get): "可以接收任意个参数,以元组形式存储" print get print get[0] print get[0][1] collect([1,2,3,4,5],"hello")([1, 2, 3, 4, 5], 'hello')
[1, 2, 3, 4, 5]
2
# -*- coding: cp936 -*- def collect(num,*get,**keyget): '''可以接收任意个参数,以元组形式存储,**收集用字典存储,并且输入调用也得按顺序\ collect('11','22',name=5,'help')这是错误的 ''' print num print get print keyget collect([1,2,3,4,5],"hello","world",['help','me'],name="wang",want="money")>>>
[1, 2, 3, 4, 5]
('hello', 'world', ['help', 'me'])
{'name': 'wang', 'want': 'money'}
>>>
6.反转过程
元组用* ,字典用**
def add(x,y):return x+y
sum=(1,2)
print add(*sum)
7作用域
>>> x=1000
>>> x
1000
>>> def foo():
x=20
>>> foo()
>>> x
1000
>>>
因为函数每个函数调用会建立个作用域
>>> x=1000
>>> x
1000
>>> def foo():
global x #声明是全局的x
x=20
>>> foo()
>>> x
20
>>>
The article write by nealgavin