Python:为什么只在分配时需要全局,而在读取时却不需要全局? [英] Python: Why is global needed only on assignment and not on reads?

查看:79
本文介绍了Python:为什么只在分配时需要全局,而在读取时却不需要全局?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果函数需要修改在全局范围内声明的变量,则需要使用全局声明.但是,如果函数只需要读取全局变量,则可以不使用全局声明而这样做:

If a function needs to modify a variable declared in global scope, it need to use the global declaration. However, if the function just needs to read a global variable it can do so without using a global declaration:

X = 10
def foo():
    global X
    X = 20 # Needs global declaration
def bar():
    print( X ) # Does not need global

我的问题是关于Python的设计:为什么Python被设计为允许在不使用全局声明的情况下读取全局变量?也就是说,为什么只强制赋值具有全局性,为什么不强制全局赋值呢? (这会使它变得平整而优雅.)

My question is about the design of Python: why is Python designed to allow the read of global variables without using the global declaration? That is, why only force assignment to have global, why not force global upon reads too? (That would make it even and elegant.)

注意:我可以看到在读取时没有歧义,但是在赋值时并不清楚是否打算创建新的局部变量或分配给全局变量.但是,我希望BDFL对这种不均衡的设计选择有更好的理由或意图.

Note: I can see that there is no ambiguity while reading, but while assigning it is not clear if one intends to create a new local variable or assign to the global one. But, I am hoping there is a better reason or intention to this uneven design choice by the BDFL.

推荐答案

看下面的代码:

from module import function

def foo(x):
    return function(x)

这里的名称function是全局名称.如果我不得不说global function来使此代码正常工作,那将变得非常乏味.

The name function here is a global. It would get awfully tedious if I had to say global function to get this code to work.

在说您的X和我的function是不同的(因为一个是变量,另一个是导入的函数)之前,请记住,Python中的所有名称都被视为相同:使用时,它们的值是在范围层次结构中查找.如果需要global X,则需要global function.哎呀.

Before you say that your X and my function are different (because one is a variable and the other is an imported function), remember that all names in Python are treated the same: when used, their value is looked up in the scope hierarchy. If you needed global X then you'd need global function. Ick.

这篇关于Python:为什么只在分配时需要全局,而在读取时却不需要全局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆