python 在内存中创建新对象时
When python creates new objects in memory
在下面的示例中,Python 对命名空间中的所有三个名称 x、y 和 z 使用内存中相同的整数对象
def main():
x = 0
y = 0
z = 0
print(x,y,z)
print(x is y is z)
y = 2
print(x,y,z)
print(x is y)
print(z is y)
print(x is z)
if __name__ == "__main__":main()
输出:
0 0 0
True
0 2 0
False
False
True
为什么 Python 在这里不使用相同的元组对象(是的,这是语言设计者的选择,但为什么)并且更好的问题是 python 何时在内存中创建新对象
def main():
a = 1, 2, 3
b = (1, 2, 3)
c = 1, 2, 3
print(type(a) == type(b))
print(a == b)
print(a is b)
print(a == c)
print(a is c)
if __name__ == "__main__":main()
输出:
True
True
False
True
False
对于表示可变对象的文字,每次对文字求值都必须生成一个新对象。
对于表示不可变对象的文字,是否创建新对象归结为任意实现细节。它可以选择使用相同的元组。它可以在未来的版本中或在不同的 Python 实现中使用相同的元组。如果您重复调用 main
,您的示例实际上 确实 重用元组,但 a
、b
和 c
的元组不同。你不应该依赖它是一种或另一种方式。
如果您想查看此案例的特定实施细节,预计算 3 个元组的 CPython bytecode compiler ordinarily merges equivalent constants together in a code object (the mechanism involves a dict, with some extra work to keep things like 1.0
and 1
from merging), but the peephole optimization pass 发生在没有重复数据删除机制的后处理阶段。
在下面的示例中,Python 对命名空间中的所有三个名称 x、y 和 z 使用内存中相同的整数对象
def main():
x = 0
y = 0
z = 0
print(x,y,z)
print(x is y is z)
y = 2
print(x,y,z)
print(x is y)
print(z is y)
print(x is z)
if __name__ == "__main__":main()
输出:
0 0 0
True
0 2 0
False
False
True
为什么 Python 在这里不使用相同的元组对象(是的,这是语言设计者的选择,但为什么)并且更好的问题是 python 何时在内存中创建新对象
def main():
a = 1, 2, 3
b = (1, 2, 3)
c = 1, 2, 3
print(type(a) == type(b))
print(a == b)
print(a is b)
print(a == c)
print(a is c)
if __name__ == "__main__":main()
输出:
True
True
False
True
False
对于表示可变对象的文字,每次对文字求值都必须生成一个新对象。
对于表示不可变对象的文字,是否创建新对象归结为任意实现细节。它可以选择使用相同的元组。它可以在未来的版本中或在不同的 Python 实现中使用相同的元组。如果您重复调用 main
,您的示例实际上 确实 重用元组,但 a
、b
和 c
的元组不同。你不应该依赖它是一种或另一种方式。
如果您想查看此案例的特定实施细节,预计算 3 个元组的 CPython bytecode compiler ordinarily merges equivalent constants together in a code object (the mechanism involves a dict, with some extra work to keep things like 1.0
and 1
from merging), but the peephole optimization pass 发生在没有重复数据删除机制的后处理阶段。