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"
  • 相关阅读:
    activity生命周期
    logcat
    URI
    intent Filter
    隐式intent
    intent
    訪问远程WAMP 下phpmyadmin
    CFileDialog的使用方法简单介绍
    JAVA wait(), notify(),sleep具体解释
    Android开发之去掉标题栏的三种方法,推荐第三种
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8033475.html
Copyright © 2011-2022 走看看