我想弄清楚最好的方法来删除的东西,最好不用写很多代码。重写__del __()是最好的选择吗?
在我的项目中,我模拟化合物 - 我通过Bond
实例将Element
实例绑定到其他Element
实例。在化学债券往往破产,我想有一个干净的方式来做到这一点。我现在的方法是一样的东西如下
# 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
是这些方式中的任何一个比其他人更喜欢这样做,还是有其他方法可以做到这一点,我忽略了?
谢谢,这基本上就是我期待我需要做的。谢谢(也)澄清德尔如何工作,我从来没有真正明白 – Dannnno