函数function
####函数
###变量名解析规则
# 按照local,nolocal,global,buildin顺序查询,对于inner来说,a=0是local,a=1是nonlocal
# nonlocal是向外走一层
def outer():
a = 1
def inner():
a = 0
print("inner:{}".format(a))
print("outer:{}".format(a))
inner()
print("~~~outer()~~~")
outer()
###可变参数 可变参数尽量使用默认值,传递参数时会从前到后匹配
###关键字参数
#关键字参数在输出结果中的顺序与调用函数时的顺序一致。
###参数默认值
###闭包
##形成闭包
# 1外函数中定义了一个内函数
# 2内函数里调用了外函数的临时变量
# 3外函数的返回值是内函数的引用
# 原理
"""一般情况下,如果一个函数结束,函数的内部所有东西都会被释放掉,还给内存,局部变量都会消失.
但是闭包是一种特殊情况,如果外函数在结束时候发现自己的临时变量将来会在内部函数中用到,
就把这个临时变量绑定给内部函数,然后自己再结束"""
###小技巧
# 函数参数进来后拷贝一份,就不会改变外面的值
def foo(xyz=[], u='abc', z=123):
xyz = xyz[:] # 影子拷贝
xyz.append(1)
print(xyz)
print("~~~copy parameters~~~")
foo()
print(foo.__defaults__)
foo()
print(foo.__defaults__)
foo([10])
print(foo.__defaults__)
foo([10, 5])
print(foo.__defaults__)
####补充
# 实参始终传递的是对象的引用而不是对象实体
# func.__defaults__ 查询默认值
# func.__doc__ 查询docstrings 说明书
-----------------------------------------
~~~outer()~~~
outer:1
inner:0
~~~copy parameters~~~
[1]
([], 'abc', 123)
[1]
([], 'abc', 123)
[10, 1]
([], 'abc', 123)
[10, 5, 1]
([], 'abc', 123)
内建函数buildinfunction
####内建函数 buildin function
# 在字典中循环时,用 items() 方法可同时取出键和对应的值:
print("~~~items()~~~")
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items():
print(k, v)
# 在序列中循环时,用 enumerate() 函数可以同时取出位置索引和对应的值:
print("~~~enumerate()~~~")
for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)
# 同时循环两个或多个序列时,用 zip() 函数可以将其内的元素一一匹配:能匹配几对就zip几对
print("~~~zip()~~~")
questions = ['name', 'quest', 'favorite color', 'a']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
print('What is your {0}? It is {1}.'.format(q, a))
# 内置函数 dir() 用于查找模块定义的名称。返回结果是经过排序的字符串列表:该函数列出所有类型的名称:变量、模块、函数等。
print("~~~dir()~~~")
import sys
print(dir(sys))
# 判断对象 isinstance(obj,class_or_tuple)
----------------------------------------
~~~items()~~~
gallahad the pure
robin the brave
~~~enumerate()~~~
0 tic
1 tac
2 toe
~~~zip()~~~
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.
~~~dir()~~~
匿名函数lambda
####匿名函数 lambda
def make_incrementor(n):
return lambda x: x + n
f = make_incrementor(42)
print("~~~lambda~~~")
print(f(1))
----------------------------------------
~~~lambda~~~
43
递归函数
自己调用自己
切记:一定要设置边界条件
函数注解
####函数注解 标注 以字典的形式存放在函数的 __annotations__ 属性中
def f(ham: str, eggs: str = "eggs") -> str:
print("annotation:{}".format(f.__annotations__))
print("arguments:", ham, eggs)
return ham + " and " + eggs
print("~~~__annotations__~~~")
print(f("spam"))
-----------------------------------------
~~~__annotations__~~~
annotation:{'ham': <class 'str'>, 'eggs': <class 'str'>, 'return': <class 'str'>}
arguments: spam eggs
spam and eggs