Python_02默认值

  • 默认值只有在最新定义的时候被评估一次
    -Example 01
A=10
def myfun(a=A):
    print(a)
A=20
myfun()
print(A)

结果

10
20
  • Example 02
A=10
A=[0]
def myfun(a=A):
    print(a)
A=[1]
myfun()
print(A)

结果

[0]
[1]
  • 如果默认值使用的是列表之类的可变数据类型,那么会在多次调用之间共享默认值
def myfun(b,a=[0]):
    a[0]+=1
    res=b+a[0]
    print(res)
myfun(1)
myfun(1)
myfun(1)

结果

2
3
4
  • 闭包函数:当内部函数调用时依然能够使用外部的变量值

  • Example 03

def myfun(a):
    def mynest(b):
        return a+b
    return mynest
f=myfun(10)#f接收mynest的定义
print(f)
print(f(100))

结果

<function myfun.<locals>.mynest at 0x00000280A926F048>
110
  • 使用闭包函数时应注意变量是否成为定值
def myfun():
    lists=["","","",""]
    for i in range(0,4):
        def mynest(b):
            return i+b
        lists[i]=mynest
    return lists
funcs=myfun() #执行完这一句后,i=3不变,因此结果均为13
print("funcs为",funcs)
print(funcs[0](10))
print(funcs[1](10))
print(funcs[2](10))
print(funcs[3](10))

结果

funcs为 [<function myfun.<locals>.mynest at 0x00000280A92ED488>, <function myfun.<locals>.mynest at 0x00000280A92ED840>, <function myfun.<locals>.mynest at 0x00000280A92ED7B8>, <function myfun.<locals>.mynest at 0x00000280A92ED730>]
13
13
13
13
  • 为了使i从0-3变化,我们可以使用默认值
  • Example 04
def myfun():
    lists=["","","",""]
    for i in range(0,4):
        def mynest(b,i=i):
            return i+b
        lists[i]=mynest
    return lists
funcs=myfun() 
print("funcs为",funcs)
print(funcs[0](10))
print(funcs[1](10))
print(funcs[2](10))
print(funcs[3](10))

结果

funcs为 [<function myfun.<locals>.mynest at 0x00000280A92ED400>, <function myfun.<locals>.mynest at 0x00000280A92EDC80>, <function myfun.<locals>.mynest at 0x00000280A92EDA60>, <function myfun.<locals>.mynest at 0x00000280A92ED9D8>]
10
11
12
13
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值