1.函數(shù)創(chuàng)建
python2版本中可以用callable()來查看是否為函數(shù),在3.0中要用hasattr (func,_call_)來查看是否為函數(shù)
使用def 來定義函數(shù),eg:
>>> def hello(name):
...? ? return 'Hello, ' + name + ' !'?
...
>>> print hello('Bruce')
Hello, Bruce !
在函數(shù)內(nèi)可以寫文檔,通過__doc__方式來訪問,eg:
>>> def square(x):
...? ? 'Calculates the square of the number x.'
...? ? return x*x
...
>>> square(5)
25
>>> square.__doc__
'Calculates the square of the number x.'
2.函數(shù)參數(shù)
>>> def try_to_change(n):
...? ? n = 'Mr.Bruce'
...
>>> name = 'Mr.Entity'
>>> try_to_change(name)
>>> name
'Mr.Entity'
上述代碼相當(dāng)于:
>>> name = 'Mr.Entity'
>>> n=name
>>> n='Mr.Bruce'
>>> name
'Mr.Entity'
字符串、數(shù)字和元組時無可變的,不能修改,其他的能修改。
這里的參數(shù)有點象C或者C++里面的傳值和傳址,但靈活很多。
關(guān)鍵字參數(shù),eg:
>>> def hello(name,greeting):
...? ? print '%s,%s!'% (greeting,name)
...
>>> hello('hello','world')
world,hello!
>>> hello('world','hello')
hello,world!
>>> hello(name='world',greeting='hello')
hello,world!
>>> hello(greeting='hello',name='world')
hello,world!
默認(rèn)值,函數(shù)定義時可以給出默認(rèn)參數(shù),eg:
>>> def hello_default(greeting = 'hello',name = 'world'):
...? ? print '%s,%s!'%(greeting,name)
...
>>> hello_default()
hello,world!
>>> hello_default('hey')
hey,world!
>>> hello_default(name='Bruce')
hello,Bruce!
>>> hello_default('hey','Bruce')
hey,Bruce!
收集參數(shù),eg:
>>>def print_params(*par):
? ? ? ? ? ? print par
>>>print_params('hello')
('hello',)
>>> print_params(1,2,3,3,5)
(1, 2, 3, 3, 5)
關(guān)鍵字參數(shù)的“收集”,eg:
>>> def print_par(x,y,z=10,*pospar,**keypar):
...? ? print x,y,z
...? ? print pospar
...? ? print keypar
...
>>>
>>> print_par(1,2,3,4,5,6,7,foo=2,bar=9,key='a')
1 2 3
(4, 5, 6, 7)
{'foo': 2, 'bar': 9, 'key': 'a'}
>>> print_par(1,2)
1 2 10
()
{}
練習(xí)使用函數(shù),eg:
.......
3.作用域
在函數(shù)內(nèi)部可以調(diào)用全局變量,如果全局變量和局部變量名稱相同則會被局部變量屏蔽
掉,但是可以通過globals()函數(shù)來實現(xiàn)全局變量的調(diào)用。eg:
>>> def combine(par):
...? ? print par+globals()['par']
...
>>> par = 'ball'
>>> combine('basket')
basketball
全局變量的聲明,eg:
>>> x=1
>>> def change_gloabl():
...? ? global x
...? ? x+=1
...
>>> change_gloabl()
>>> x
2
嵌套作用域,沒有怎么理解,需要再看看
4.遞歸? 自己調(diào)用自己
小結(jié):
1.函數(shù)定義
2.參數(shù)
3.作用域
4.遞歸