do_global()在Python教程中的效果

时间:2019-02-12 09:36:03

标签: python

遇到以下代码时,我正在读section 9.2.1有关名称空间和范围的信息。

def scope_test():
    def do_local():
        spam = "local spam"
    def do_nonlocal():
        nonlocal spam
        spam = "nonlocal spam"
    def do_global():
        global spam
        spam = "global spam"
    spam = "test spam"
    do_local()
    print("After local assignment:", spam)
    do_nonlocal()
    print("After nonlocal assignment:", spam)
    do_global()
    print("After global assignment:", spam)

scope_test()
print("In global scope:", spam)

文档声称以下是输出:

After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam

我的问题如下:由于在global spam函数中使用了global关键字,第3行的输出不应该为do_global()吗?

2 个答案:

答案 0 :(得分:2)

否,默认情况下,它在函数作用域内是局部的,除非您另外明确声明。来自Python Programming FAQ

  

在Python中,仅在函数内部引用的变量是隐式全局的。如果在函数体内任何位置为变量分配了值,除非明确声明为全局变量,否则假定该变量为局部变量。

请注意,您可以访问任何范围的全局变量的值,为此,您可以访问当前范围的任何父范围的值,但是除非您明确声明将使用global关键字对其进行修改,其值无法更改。

答案 1 :(得分:0)

这里的文档是正确的-只需尝试代码以确保...

您是正确的一点:由于module.exports = function(context) { const fs = require('fs'); if (context && context.argv) { let theme; for (let i = 0; i < context.argv.length; i++) { let argument = context.argv[i]; if (argument.indexOf('theme.') > -1) { theme = argument; break } } theme = (theme) ? theme: 'theme.defaultTheme'; // default theme const themeName = theme.split('.')[1]; fs.copyFileSync('src/theme/' + themeName + '/variables.scss', 'src/theme/variables.scss'); } }; 包含ionic cordova build android --prod --release -- --theme.themeName ,因此它将更改全局变量viewer.search的值。但是在位置3中打印的是viewer.search('keyword', function(dbids){ if(dbids instanceof Array && dbids.length) viewer.select(dbids) }) 函数中的do_global变量,global spam尚未更改。

第4张印刷品确实显示了spam中设置的全局spam的内容。