Python入門シリーズ:References

1881 ワード

References
オブジェクトを作成して変数に割り当てると、この変数は(refer to)オブジェクトに関連付けられているだけで、そのオブジェクト自体を表すものではありません.これは、変数名がコンピュータのメモリにオブジェクトが保存されている場所を指していることを意味します.これを変数名をオブジェクトにバインドする(This is called as binding of the name to the object).
通常、この問題にあまり注目する必要はありませんが、あなたのアプリケーションに微妙な影響を与えるので、この問題を意識する必要があります.
次の例を参照してください.
# Filename: reference.py
print('Simple Assignment')
shoplist = ['apple', 'mango', 'carrot', 'banana']
mylist = shoplist # mylist is just another name pointing to the same
object!
del shoplist[0] # I purchased the first item, so I remove it from the
list
print('shoplist is', shoplist)
print('mylist is', mylist)
# notice that both shoplist and mylist both print the same list without
# the 'apple' confirming that they point to the same object
print('Copy by making a full slice')
mylist = shoplist[:] # make a copy by doing a full slice
del mylist[0] # remove first item
print('shoplist is', shoplist)
print('mylist is', mylist)
# notice that now the two lists are different

出力結果:
$ python reference.py
Simple Assignment
shoplist is ['mango', 'carrot', 'banana']
mylist is ['mango', 'carrot', 'banana']
Copy by making a full slice
shoplist is ['mango', 'carrot', 'banana']
mylist is ['carrot', 'banana']

プロセスの実行:
プログラムの注釈部分では、listや類似のsequenceオブジェクトや他の複雑なレプリケーション操作をしたい場合(integerのような簡単なオブジェクトはこの問題を考慮する必要はありません)、slicing操作を使用してレプリケーションを完了することに注意してください.1つの変数名だけを別の変数名に割り当てると、2つの変数は同じオブジェクトを指します.もしあなたがそれに気づかなかったら、あなたに不要な面倒をもたらします.
説明:この文章はA bytte of Python v 1から.92 for Python3.0翻訳してきたので、指摘してください.