我试图找出删除内容的最佳方法,最好不必编写大量代码.
在我的项目中,我正在模拟化合物 – 我通过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
这些方法中的任何一种方法都优于其他方式,还是有其他方法可以做到这一点我忽略了?
解决方法:
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 "", line 1, in
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%的时间,所以它肯定不是处理你的情况的正确方法.
标签:python,python-2-7,override,del
来源: https://codeday.me/bug/20190529/1174962.html