python方法重写的好处,python – 重写__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

这些方法中的任何一种方法都优于其他方式,还是有其他方法可以做到这一点我忽略了?

解决方法:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值