第七章 函数
函数中的参数名称为 形参 而你提供给函数调用的值称为实参
当在函数定义内声明变量的时候,它们与函数外具有相同名称的其他变量没有任何关系,即变量名称对于函数来说是局部的。这称为变量的作用域 。
def func(x):
print 'x is',x
x=2
print 'Changed local x to',x
x=50
func(x)
print 'x is still',x
输出:
x is 50
Changed local x to 2
x is still 50
Changed local x to 2
x is still 50
——————————————————————————————————————
global语句被用来声明x是全局的,可以使用同一个global语句指定多个全局变量。例如global x, y, z。
def func()
global x
print 'x is',x
x=2
print 'Changed local x to',x
x=50
func()
print 'Value of x is',x
输出:
x is 50
Changed global x to 2
Value of x is 2
Changed global x to 2
Value of x is 2
————————————————————————————————————————
使用默认参数值
如果用户不想要为这些参数提供值,这些参数就使用默认值。更加准确的说,默认参数值应该是不可变的。(后面补充)
python什么是可变的什么是不可变的。
python中,万物皆对象。python中不存在所谓的传值调用,一切传递的都是对象的引用,也可以认为是传址。
python中,对象分为可变(mutable)和不可变(immutable)两种类型。
元组(tuple)、数值型(number)、字符串(string)均为不可变对象,而字典型(dictionary)和列表型(list)的对象是可变对象。
python中,对象分为可变(mutable)和不可变(immutable)两种类型。
元组(tuple)、数值型(number)、字符串(string)均为不可变对象,而字典型(dictionary)和列表型(list)的对象是可变对象。
def say(message, times = 1):
print message * times
say('Hello')
say('World', 5)
输出:
Hello
WorldWorldWorldWorldWorld
WorldWorldWorldWorldWorld
只有在形参表末尾的那些参数可以有默认参数值,例如,def func(a, b=5)是有效的,但是def func(a=5, b)是 无效 的。
————————————————————————————————————————
关键参数
某个函数有许多参数,而你只想指定其中的一部分,那么你可以通过命名来为这些参数赋值——这被称作 关键参数 ——我们使用名字(关键字)而不是位置来给函数指定实参。像楼上例子say('World',5)可以改成say(times=5,message='World')。而say(times=5,'World')是错的。
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)
输出:
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
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50
在第二次使用函数func(25, c=24)的时候,根据实参的位置变量a得到值25。根据命名,即关键
参数,参数c得到值24。变量b根据默认值,为5。(尼玛。。。这就是所谓的关键参数。。。起名这么高深莫测干嘛。。。)
参数,参数c得到值24。变量b根据默认值,为5。(尼玛。。。这就是所谓的关键参数。。。起名这么高深莫测干嘛。。。)
——————————————————————————————————————————————————
return 语句
没有返回值的return语句等价于return None。函数someFunction没有使用return语句,如同:
def someFunction():
pass
pass语句在Python中表示一个空的语句块。
pass
pass语句在Python中表示一个空的语句块。
写个函数def dothing(): 内容是空的,不行,用pass,一个是为了格式对齐,一个是为了语义.
——————————————————————————————————————————————————
DocStrings
DocStrings
文档字符串。
def printMax(x,y):
"""Print 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__
输出:
5 is maximum
Prints the maximum of two numbers.
Prints the maximum of two numbers.
The two values must be integers.
在函数的第一个逻辑行的字符串是这个函数的 文档字符串 。注意,DocStrings也适用于模块和类
文档字符串的惯例是一个多行字符串,它的首行以大写字母开始,句号结尾。第二行是空行,从第三行开始是详细的描述。 强烈建议 你在你的函数中使用文档字符串时遵循这个惯例。
使用__doc__(前后都是两个_下划线)调用printMax函数的文档字符串属性(属于函数的名称)。
help(printMax) #记住按q退出help。
输出:
Help on function printMax in module __main__:
printMax(x, y)
Print the maximum of two numbers.
The two values must be integers.
printMax(x, y)
Print the maximum of two numbers.
The two values must be integers.