gpt4 book ai didi

python - 别名是否保证在 Python 中引用同一个对象?

转载 作者:太空宇宙 更新时间:2023-11-03 12:47:55 24 4
gpt4 key购买 nike

Python docs提到以下关于名称是对象的别名的内容:

Objects have individuality, and multiple names (in multiple scopes) can be bound to the same object. This is known as aliasing in other languages. This is usually not appreciated on a first glance at Python, and can be safely ignored when dealing with immutable basic types (numbers, strings, tuples). However, aliasing has a possibly surprising effect on the semantics of Python code involving mutable objects such as lists, dictionaries, and most other types. This is usually used to the benefit of the program, since aliases behave like pointers in some respects. For example, passing an object is cheap since only a pointer is passed by the implementation; and if a function modifies an object passed as an argument, the caller will see the change — this eliminates the need for two different argument passing mechanisms as in Pascal.

在其他一些高级语言中,出于性能原因,原始类型通常是特殊情况,并且被复制而不是被引用。例如,在 Java 中:

int a = 20000;
int b = a;

上面的代码将复制值 20000,而不是指向值 20000 的指针。在这种情况下,ab 可能会占据内存中的不同位置。由于 == 上的特殊大小写仅测试基本类型的相等性而不是同一性,因此我不认为可以在普通代码中反省此行为。

另一方面,在 Python 3 中使用 intstr 等类型进行的有限测试表明,确实是指针而不是值被复制,如文档:

a = 20000
b = a
a is b # True

这是一个非常好的属性,它使语言非常一致,因为原始类型没有特殊的大小写。所有赋值都将名称重新分配给另一个对象。但是,出于性能原因,Python 解释器是否有可能处理特殊情况类型,例如 int

因此,我的问题是:基本类型的这个属性是否有保证?换句话说,在 b = a 之后,比较 a is b 是否总是为 True,无论使用何种 Python 解释器?

最佳答案

b = a 使名称 ba 引用完全相同的对象。所以是的,在 Python 中,a is b 将始终为 True。

关于python - 别名是否保证在 Python 中引用同一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25314899/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com