引用全局图元与对象 [英] Referencing global primitives vs. objects

查看:77
本文介绍了引用全局图元与对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以在Python中解释以下结果吗?

Could someone please explain the following result in Python?

运行以下代码段时,Python引发错误,指出变量x在赋值之前已被引用:

When running the following snippet of code, Python throws an error, saying that the variable x was referenced before assignment:

x = 1

def increase_x():
    x += 1

increase_x()

当然,解决方案是在increase_x的函数声明之后包括行global x.

The solution, of course, would be to include the line global x after the function declaration for increase_x.

但是,当运行下一个代码片段时,没有错误,结果就是您所期望的:

However, when running this next snippet of code, there is no error, and the result is what you expect:

x = [2, -1, 4]

def increase_x_elements():
    for k in range(len(x)):
        x[k] += 1

increase_x_elements()

这是因为整数是Python(而不是对象)中的基元,因此第一个代码段中的x是存储在内存中的基元,而第二个代码段中的x则引用了指向列表对象的指针?

Is this because integers are primitives in Python (rather than objects) and so x in the first snippet is a primitive stored in memory while x in the second snippet references a pointer to a list object?

推荐答案

正如Ffisegydd所指出的那样,Python中没有像原始的东西:一切都是对象.

As Ffisegydd points out, there is no such thing as a primitive in Python: everything is an object.

不过,您应该注意,您在这两个摘要中正在执行两个完全不同的事情.在第一个中,您将x重新绑定到x + 1的值.通过尝试分配给x,您已经使其在本地范围内,因此您对x + 1的引用失败.

You should however note that you are doing two completely different things in those two snippets. In the first, you are rebinding x to the value of x+1. By attempting to assign to x, you've made it locally scoped, so your reference to x+1 fails.

在第二个片段中,您正在修改x的内容,而不是重新绑定它.之所以可行,是因为列表是可变的,但区别不是可变与不可变而是可变与重新绑定:重新绑定可变对象将失败,就像整数一样.

In the second snippet, you are modifying the contents of x, rather than rebinding it. This works because lists are mutable, but the difference is not mutable vs immutable but mutating vs rebinding: rebinding a mutable object would fail just as doing so with an integer does.

这篇关于引用全局图元与对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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