的Python通過引用傳遞參數,所以基本上是「字符串」你進入B()
實際上是一個指針(存儲器地址),以實際的字符串。如果您在執行示例腳本時查看每個對象,您會發現它們都是一樣的。
例如,這個版本打印傳遞的對象(使用object.__repr__
因爲str.__repr__
打印數據)的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()
時,它是相同的對象:實際上是一個指向字符串的指針。
這很少消耗額外的內存。