[Python] Understand Scope in Python

本文深入探讨了Python中作用域的概念,包括局部作用域、非局部作用域和全局作用域,并通过示例展示了如何使用'nonlocal'关键字来修改外部作用域内的变量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Misunderstanding scope can cause problems in your application. Watch this lesson to learn how Python scope works and the hidden implications it presents. Local scope, nonlocal scope, and global scope variables are demonstrated and explained.

 

For example, we have the code:

def whoami():
    def local_groot():
        i = "I am local groot"
        print(i) #"I am local groot"

    i = "I am groot"
    print(i) # "I am groot"

    # Call the local groot function
    local_groot()
    print(i) # "I am groot"

Each function has its scope, won't conflict with outside function scope's variable.

 

For the case you do want to overwrite:

def whoami():
    def local_groot():
        i = "I am local groot"
        print(i)

    def nonlocal_groot():
        nonlocal i
        i = "I am nonlocal groot"

    i = "I am groot"
    print(i) #"I am groot"
    nonlocal_groot()
    print(i) #"I am nonlocal groot"

We can use 'nolocal' keyword.

 

There is also 'global' keyword, but you don't want to use it, it is not good pratice:

    def global_groot():
       global i
        i = "I am global groot"

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值