迈向大神 —1 函数(二)
补充 可读性强 复用性强
补充
def qqxing(k,l = {}):
# l.append(1)
l[k] = 'v'
print(l)
qqxing(1) #[1]
qqxing(2) #[1,1]
qqxing(3) #[1,1,1]
如果默认参数的值是一个可变数据类型,
那么每一次调用函数的时候,
如果不传值就公用这个数据类型的资源
命名空间和作用域
-
全局命名空间 在程序从上到下执行的过程中 依次加载内存中 –我们写的代码 不是函数中的代码
-
局部命名空间 函数内部定义的名字 当函数被调用 才会产生名称空间 --* 函数*
-
内置命名空间 input() python解释器已启动就可以使用 内置的名字在启动时被加载到内存里–python 解释器
在全局不能用局部中使用
import this
p =max([1,2,3])
当我们在全局定义了和内置名字空间同名的名字是 会使用自己的
函数的内存地址() --》》函数调用
对于不可变数据类型 在局部可是查看全局作用域中的变量 但是不能更该
若修改需要global
a=1
def func()
global a#可修改全局(少用不安全) 尽量接收参数 return 返回值
a+=1
print(a)
a=1
def func()
x='aaa'
t='bbb'
print(locals())#局部名字的所有名字 与所在位置有关系 作用域有哪些名字 #本地的
print(a)
print(globals()) #所有命名的名字
函数的嵌套套用
def max(a,b):
return a if a>b else b;
def max_m(x,y,z):#函数嵌套调用
return max(max(x,y),z)
print(max_m(55,6,99))
函数的嵌套定义 排除错误从下往上找
def outer():
def inner():
print("you are so beautiful!")
inner()
outer()
#nonlocal a 声明了一个上层的局部变量名 对局部最近一层有影响
# a = 1
# def outer():
# a = 1
# def inner():
# a = 2
# def inner2():
# nonlocal a #声明了一个上面第一层局部变量
# a += 1 #不可变数据类型的修改
# inner2()
# print('##a## : ', a)
# inner()
# print('**a** : ',a)
# outer()
# print('全局 :',a)
函数名就是内存地址 函数名可以赋值 函数名可以作为容器类型的元素 函数名可以作为函数参数 可以作为返回值
函数名就是一类对象
闭包
含义 嵌套函数 内部函数调用外部函数的变量
def ouster():
a=1
def inner():
print(a) #调用a
print(inenr.__closure__) #显示 cell 是一个闭包
ouster()
闭包 记住里面的函数的id 不然它消失 这样永远不会消失 延长生命周期
def ouster():
a=1
def inner():
print(a) #调用a
return inner #以返回值的形式返回给 outst
print(inenr.__closure__) #显示 cell 是一个闭包
inn=ouster() #
inn() #外部去使用内部的
#爬虫
#import urllib #模块
from urllib.request import urlopen
# ret=urlopen('http://www.baidu.com').read()
# print(ret)
def get_url():
url='http://www.baidu.com'
def get():
ret = urlopen(url).read()
print(ret)
return get
get_func=get_url()
三元运算符
c=a if a>b else b
true if 条件 else false