zoukankan      html  css  js  c++  java
  • [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"
  • 相关阅读:
    前端之CSS
    前端之HTML
    数据库作业案例
    django进阶版4
    django进阶版3
    django进阶版2
    django初步了解4
    django进阶版1
    django初步了解3
    django初步了解2
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8033475.html
Copyright © 2011-2022 走看看