[Python] Understand Scope in Python

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"

 

posted @ 2017-12-13 16:18  Zhentiw  阅读(273)  评论(0编辑  收藏  举报