python学习笔记(03):函数

全局变量:

 1 global.x=5 

默认参数值:

  只有在行参表末尾的哪些参数可以有默认参数值,即

def func(a, b=5 )#有效的
def func( a=5,b )#无效的

关键参数:

#!/usr/bin/python
# Filename: func_key.py
def func(a, b=5, c=10):
    print 'a is', a, 'and b is', b, 'and c is', c
func(3, 7)
func(25, c=24)
func(c=50, a=100)
#输出:
$ python func_key.py
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50

return语句:和c语言同,省略~~~大声笑

DocStrings(文档字符串):

#!/usr/bin/python
# Filename: func_doc.py
def printMax(x, y):
    '''Prints the maximum of two numbers.
    The two values must be integers.'''
    x = int(x) # convert to integers, if possible
    y = int(y)
    if x > y:
        print x, 'is maximum'
    else:
        print y, 'is maximum'
printMax(3, 5)
print printMax.__doc__

结果:

$ python func_doc.py
5 is maximum
Prints the maximum of two numbers.
        The two values must be integers.

在函数的第一个逻辑行的字符串是这个函数的 文档字符串 。

注意,DocStrings也适用于模块和类,
文档字符串的惯例是一个多行字符串,它的首行以大写字母开始,句号结尾。第二行是空行,从第三行开
始是详细的描述。

你可以使用__doc__(注意双下划线)调用printMax函数的文档字符串属性(属于函数的名称)。

如果你已经在Python中使用过help(),那么你已经看到过DocStings的使用了!它所做的只是抓取函数
的__doc__属性,然后整洁地展示给你。你可以对上面这个函数尝试一下——只是在你的程序中包
括help(printMax)。记住按q退出help。
自动化工具也可以以同样的方式从你的程序中提取文档。因此,我 强烈建议 你对你所写的任何正式函数编
写文档字符串。随你的Python发行版附带的pydoc命令,与help()类似地使用DocStrings。

posted @ 2014-08-13 18:10  西瓜没有皮  阅读(132)  评论(0编辑  收藏  举报