6

できれば多くのコードを書かなくても、何かを削除する最善の方法を見つけようとしています。

私のプロジェクトでは、化合物をシミュレートしています。インスタンスを介しElementて他のインスタンスに結合されたインスタンスがあります。化学では結合が壊れることがよくありますが、それをきれいに行う方法が必要です。私の現在の方法は次のようなものですElementBond

# aBond is some Bond instance
#
# all Element instances have a 'bondList' of all bonds they are part of
# they also have a method 'removeBond(someBond)' that removes a given bond 
# from that bondList
element1.removeBond(aBond)
element2.removeBond(aBond)
del aBond

私は何かをしたい

aBond.breakBond()

class Bond():
    def breakBond(self):
        self.start.removeBond(self) # refers to the first part of the Bond 
        self.end.removeBond(self) # refers to the second part of the Bond 
        del self

代わりに、このようなものは問題ありません

del aBond

class Bond():
    def __del__(self):
        self.start.removeBond(self) # refers to the first part of the Bond 
        self.end.removeBond(self) # refers to the second part of the Bond 
        del self

これらの方法のいずれかが他の方法よりも好ましいですか、それとも私が見落としている他の方法がありますか?

4

2 に答える 2

6

Python はガベージ コレクションを使用してメモリを管理します。つまり、何も削除する必要はありません。このクラスは問題ありません:

class Bond():
    def breakBond(self):
        self.start.removeBond(self)
        self.end.removeBond(self)

メモリから何も削除しないdelことに注意してください! オブジェクトへの参照を削除するだけですが、オブジェクトは複数の参照を持つことができます。

>>> some_list = [1,2,3]
>>> b = some_list
>>> del b   # destroys the list?
>>> b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined
>>> some_list   # list is still there!
[1, 2, 3]
>>> c = some_list
>>> del some_list
>>> c        # list is still there!
[1, 2, 3]
>>> del c

最後del cの後、インタプリタはリストの割り当てを解除できます。CPython では、割り当て解除はすぐに行われますが (この単純なケースでは)、言語の他の実装では、インタープリターはリストをすぐに割り当て解除しない場合があります。

__del__のドキュメントがこの事実を引用していることにも注意してください。さらに、これは非常に低レベルの方法であり、99.9% の時間は必要ないため、状況を処理する正しい方法ではありません。

于 2014-02-13T22:14:34.967 に答える