自定义函数
使用 def 关键词,函数说明文档可以放在三引号里面,可以使用add_f._ _ doc_ _或者help(add_f)来查看
def add_f(x,y):
'''
just a test
'''
return(x+y)
return : 中止函数并得到返回值,可以返回一个对象,也可以返回多个对象
传参的方法
-
按照位置传参
>>> add_f(1,2) 3
-
根据名称
>>> add_f(x=1,y=2) 3
-
设置默认值
def add_f(x,y=5): ''' just a test ''' return(x+y) # y 使用默认值 a(1) 6 #y 使用传参值覆盖默认值 a(1,2) 3
返回值和参数搜集
-
返回值
>>> def test(x,y): ''' just a test ''' return x,y #返回值构成了一个元组 >>> test(1,2) (1, 2) #可以用于赋值语句 >>> a,b=test(1,2)
-
参数收集
*args
**kwargs
这里的星号并不是args 的组成部分,其实是一个标记。# args收集参数为一个列表 >>> def test(*args): print ("args:",args) >>> test(1,2,3) args: (1, 2, 3) # args收集参数为一个字典 >>> def test(**kwargs): print ("args:",kwargs) >>> test(a=1,b=2) args: {'a': 1, 'b': 2}
嵌套函数
嵌套函数:一个函数体里含有另外一个函数
-
函数是对象,可以作为一个参数被另一个函数的参数所引用:
>>> def test(a,b): print ([a(i) for i in b]) >>> test(abs,[1,2,3]) [1, 2, 3]
-
函数可以作为函数值
变量的作用域
-
全局作用域
-
本地作用域
global:指定当前变量使用外部的全局变量
nonlocal:指定当前变量为外层的变量#bar 这个内部函数使用的x在这个变量的作用域内,没有定义,所以会报错。 >>> def test(): x=2 def bar(): x+=2 return (x) return bar() >>> test() Traceback (most recent call last): File "<pyshell#159>", line 1, in <module> test() File "<pyshell#158>", line 6, in test return bar() File "<pyshell#158>", line 4, in bar x+=2 UnboundLocalError: local variable 'x' referenced before assignment #指定使用全局变量 >>> def test(): x=2 def bar(): global x x+=2 return (x) return bar() >>> x=1 >>> test() 3 #指定使用外层作用域的变量 >>> def test(): x=2 def bar(): nonlocal x x+=2 return (x) return bar() >>> test() 4