关于不定长参数和内存地址复用的问题(闭包与装饰器,修改外部函数变量与修改全局变量)

__nonlocal:__修改外部函数的变量

__global:__修改全局变量

def test3(**kwargs):
    print("这是有不定长参数的函数")
    # 下面这么写会报错,因为一个*是一个函数,如传入a = 3.右边的*会将a = 3的key拆出来(a),左边的*会将a继续拆分。这样会报错
    print(**kwargs)
    
test3(a = 3)

def test3(**kwargs):
    print("这是有不定长参数的函数")
    print(*kwargs)
# 这样会把他的key拆出来    
test(a = 3)
# ip地址1,3一样,2,4一样。是因为第1次创建了一个变量指向decorator(),第2次又创建了一个变量指向decorator()。
# 第3次的时候发现第1次的指向没用.会重新复用第1次的地址。第4次的时候发现第2次的没用,会重新复用第2次的地址
def decorator():
    i = 1
    
    def inner():
        print("login", i)
    return inner


say = decorator()
print("1:", id(say))
say = decorator()
print("2:", id(say))
say = decorator()
print("3:", id(say))
say = decorator()
print("4:", id(say))

say()

运行结果:
1: 140566030047160
2: 140566030047296
3: 140566030047160
4: 140566030047296
login 1

def decorator(fn):
    def inner():
        print("login")
        fn()
    return inner

def say():
    print("say")
    
# 第一个fn = 函数say的引用 变量say = inner
say = decorator(say)      # 第一次等于inner   fn = say()


# 第二个fn = 第一个变量say = inner 第二个变量say = inner + inner
# say = inner
say = decorator(say) # 第二个 fn  innner-------inner  ------fn say ()


# 第三个fn = 第二个变量say = inner + inner 第三个变量say = inner + inner + inner
say = decorator(say)  # 第三次 fn inner ----inner ----inner ----fn say()
# print("1:", id(say))

# print("2:", id(say))

# print("3:", id(say))

# 因为后面的把前面的覆盖了所以say只输出了一次,login输出了三次
say1()

运行结果:
login
login
login
say

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值