在Python中将列表定义为全局变量 [英] Defining lists as global variables in Python

查看:1043
本文介绍了在Python中将列表定义为全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个列表,其中一些功能在我的程序中起作用。这实际上是一个共享列表,我的所有功能都可以对其进行编辑。是否真的有必要在所有函数中将其定义为全局?



我的意思是将全局关键字放在每个使用它的函数中,或者在外部定义它所有的函数是足够的,而不使用它的定义背后的全球词?

解决方案当您分配一个变量( x = ... ),您正在当前范围中创建一个变量(例如,当前函数的本地变量)。如果它恰好映射到外部(例如全局)范围的变量,那么太糟糕了 - Python不关心(这是件好事)。所以你不能这样做:

  x = 0 
def f():
x = 1
f()
print x#=> 0

并期望 1 。相反,您需要声明您打算使用全局x

  x = 0 
def f():
global x
x = 1
f()
print x#=> 1

但请注意,赋值变量与方法调用非常不同。你可以随时调用任何范围内的方法 - 例如对于来自外部(例如全局)范围的变量,因为没有局部影响他们。



非常重要:成员赋值( x.name = ... ),项目分配( collection [key] = ... ), code> sliceable [start:end] = ... ),并且更多的是所有的方法调用!因此,您不需要 global 来更改全局成员或调用它的方法(即使它们改变对象)。


I am using a list on which some functions works in my program. This is a shared list actually and all of my functions can edit it. Is it really necessary to define it as "global" in all the functions?

I mean putting the global keyword behind it in each function that uses it, or defining it outside of all the functions is enough without using the global word behind its definition?

解决方案

When you assign a variable (x = ...), you are creating a variable in the current scope (e.g. local to the current function). If it happens to shadow a variable fron an outer (e.g. global) scope, well too bad - Python doesn't care (and that's a good thing). So you can't do this:

x = 0
def f():
    x = 1
f()
print x #=>0

and expect 1. Instead, you need do declare that you intend to use the global x:

x = 0
def f():
    global x
    x = 1
f()
print x #=>1

But note that assignment of a variable is very different from method calls. You can always call methods on anything in scope - e.g. on variables that come from an outer (e.g. the global) scope because nothing local shadows them.

Also very important: Member assignment (x.name = ...), item assignment (collection[key] = ...), slice assignment (sliceable[start:end] = ...) and propably more are all method calls as well! And therefore you don't need global to change a global's members or call it methods (even when they mutate the object).

这篇关于在Python中将列表定义为全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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