假设我有一个 1 MB 的文本文件。考虑以下示例:
class A:
def __init__(self, file):
self.file = file
class B:
def __init__(self, file):
self.a = A(file)
f = open(path, 'r')
file = f.read()
f.close()
x = B(file)
我是否创建了两个文件并因此浪费了 2 兆字节而不是 1 兆字节?或者 python 识别文件对象并仅提供对原始文件的引用?
附带问题:在这种情况下使用全局变量是否更好?
请您参考如下方法:
Python 通过引用传递参数,因此本质上,您传递给 B() 的“字符串”实际上是指向实际字符串的指针(内存地址)。如果您查看示例脚本执行过程中每个点的对象,您会发现它们都是相同的。
例如,此版本打印传递对象的 repr()(使用 object.__repr__ 因为 str.__repr__ 打印数据):
class A:
def __init__(self, f):
print(repr(self), "received", object.__repr__(f))
self.f = f
class B:
def __init__(self, f):
print(repr(self), "received", object.__repr__(f))
self.a = A(f)
with open(LARGE_FILE, 'rb') as f:
text = f.read()
print("passing", object.__repr__(f), "into B()")
x = B(text)
结果是这样的:
passing <str object at 0x280f960> into B()
<__main__.B object at 0x290acd0> received <str object at 0x280f960>
<__main__.A object at 0x290add0> received <str object at 0x280f960>
如您所见,当字符串变量被传递给A() 和B() 的构造函数时,它是同一个对象:实际上是指向字符串。
这会消耗很少的额外内存。
