[Python]核心编程之函数

来源:互联网 发布:大数据抓小偷 编辑:程序博客网 时间:2024/05/16 14:27

一、什么是函数

(1)函数和过程

    过程一般无返回值,Python中函数默认返回None。

(2)返回值与函数类型

    同上,Python在没有return语句时返回None。Python中的多返回值可以放到容器中,比如列表、元组等等。

def foo():    print "foo called."print foo()

foo called.
None
二、调用函数

(1)函数操作符('()')

(2)关键字参数

def bar(x):    print xbar(2);bar('apple');bar(['T','NIL'])bar(x=2);bar(x='apple');bar(x=['T','NIL'])

2
apple
['T', 'NIL']
2
apple
['T', 'NIL']

(3)默认参数

    声明了默认值的参数即默认参数,因为参数有默认值,所以函数调用时,可以不向该参数传值是允许的。默认参数必须位于形参的末尾,即默认参数的后面只能跟着默认参数。

def net_conn(host,port=8080):    print "host:",host    print "port:",portnet_conn('del_pc','5050')net_conn('chino')

host: del_pc
port: 5050
host: chino
port: 8080

(4)参数组

    Python允许程序员执行一个没有显示定义参数的函数,相应的方法是通过把一个元组(非关键字参数)或字典(关键字参数)作为参数传递给函数。基本上可以将所有参数放进一个元组或者字典中,仅仅用这些装有元素的容器来调用一个函数:

func(*tuple_grp_nonkw_args, **dict_grp_kw_args)

其中的tuple_grp_nonkw_args是以元组形式体现的非关键参数组,dict_grp_kw_args是装有关键字参数的字典。

实际上也可以给出标准的位置参数和关键字参数,所以Python中允许的函数调用的完整语法为:

func(positional_args,keyword_args,*tuple_grp_nonkw_args,**dict_grp_kw_args)

三、创建函数

(1)def语句

    完整的语法:

def function_name(arguments):

    "fucntion_documentation_string"

    function_body_suite

def helloSomeone(who):    '''returns a salutory string customized with the input'''    return "Hello " + str(who)print helloSomeone('Joe')

(2)声明与定义

    Python中将声明和定义视为一体。

(3)前向引用

    Python允许在函数定义中使用另一个前面未定义的函数,即相面的情形是可以的:

def foo():    print "In foo()"    bar()def bar():    print "In bar()"    foo()

只要保证调用时,函数已经定义即可。

(4)函数属性

    foo.__doc__

    foo.__dict__

...

(5)内部/内嵌函数

def foo():    def bar():        print "bar() called"    print "foo() called"    bar()foo()

(6)函数(与方法)装饰器

@decorator(dec_opt_args)

def func2Bdecorated(func_opt_args):

    :

staticmethod()  classmethod()

四、传递参数

五、形式参数(Formal Arguments)

(1)位置参数

(2)默认参数

六、可变长度的参数

(1)非关键字可变长参数(元组)

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

(3)调用带有可变长参数对象函数

def foo(x,*nonkw,**kw):    print "x:",x    for e in nonkw:        print e    for key in kw:        print key,':',kw[key]        foo(100,*('This','is','tuple'),**{'me':10,'y':37})

x: 100
This
is
tuple
me : 10
y : 37

foo(3.14,3,4,5,[5,3],y=4.33,z=9.87)
x: 3.14
3
4
5
[5, 3]
y : 4.33
z : 9.87

七、函数式编程(*)

(1)全局变量与局部变量

(2)global语句

n = 100def foo():    m = 50    def bar():        print "in bar()"        n = 4        print n        print m    print m    bar()foo()print n

50
in bar()
4
50
100

n = 100def foo():    m = 50    def bar():        print "in bar()"        global n        n = 4        print n        print m    print m    bar()foo()print n

50
in bar()
4
50
4












0 0