Python中的全局变量? [英] Global variables in Python?

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

问题描述

我对python中的全局变量有疑问. 如果我正确理解了这一点,则可以从该类中的每个方法读取我在该类中定义的所有变量. 现在我以为只有在之前用全局'variableName'标记全局变量的情况下,我才可以写入全局变量.但是,这让我感到惊讶:

I have a question about global variables in python. If I got this correctly, all variables that I define in my class can be read from each method in this class. Now I thought that I could only write into the global variables if I mark them with global 'variableName' before. But here is what freaks me out:

def foo(a):
    for i in range(a[0].__len__()):
        a[0][i] -= a[1][i]
a = [[0,1,2,3,4,5,6],[0,1,2,3,4,5,6]]
foo(a)
print(a)

给我

[[0, 0, 0, 0, 0, 0, 0], [0, 1, 2, 3, 4, 5, 6]]

但是为什么?我的意思是,我从未取消过'global a'.

But WHY? I mean, I never decleared 'global a'.

奇怪的是,如果我这样做:

Strange thing is, if i do:

def foo(a):
    a -= 1
a = 2
foo(a)
print(a)

这为什么给我

2

我不明白区别:/

推荐答案

您的函数定义有问题.您将两个函数都作为参数传递,因此不必首先声明全局的任何内容.如果您要从定义中删除参数,那么这个问题会更有意义.

You have a problem with your function definitions. You are passing both functions an argument, thus making it unnecessary to declare anything global in the first place. If you would remove the arguments from your definitions, this question would make a little more sense.

这里的整个混乱在于python中数据类型的可变性.列表和字典是可变容器,这意味着它们的值可以随时更改.其他数据类型(例如整数,浮点数,元组等)是不可变的.您不能更改它们.您可以创建一个新的整数,例如1 + 1将返回一个新的整数2.

The whole confusion here lies within mutability of data types in python. Lists and dictionaries are mutable containers, which means that their values can be changed at any time. Other data types, like integers, floats, tuples and so on are immutable. You cannot change them. You can create new ones, like 1 + 1 will return a new integer 2.

在第一个示例中,您正在修改列表的内容.列表是可变容器,这意味着它们的内容可以更改.如果您恰好在全局范围内具有a,则该范围内的函数可以修改列表的内容.

In your first example, you're modifying the contents of a list. Lists are mutable containers which means that their contents can change. If you happen to have a in the global scope, then a function in that same scope can modify the contents of the list.

def foo():
    """ Notice i've removed the argument `a` from the function def, to illustrate my point.. """
    for i in range(a[0].__len__()):
        a[0][i] -= a[1][i]
>>> a = [[0,1,2,3,4,5,6],[0,1,2,3,4,5,6]]
>>> foo()
>>> print(a)
[[0, 0, 0, 0, 0, 0, 0], [0, 1, 2, 3, 4, 5, 6]]

在第二个示例中,您正在修改一个整数.整数是不可变的数据类型,无法修改.以下在函数foo()的局部范围内修改变量a(通过创建新的整数),但是由于您尚未全局定义a或返回局部a,没有明显的变化.

In your second example, you're modifying an integer. Integers are immutable data types and cannot be modified. The following will modify the variable a (by creating a new integer) in the local scope of function foo() but because you have not defined a global or return the local a, there's no visible change.

def foo(a):
    a -= 1
>>> a = 2
>>> foo(a)
>>> print(a)
2

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

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