Is __del __ () the best choice here?

I am trying to find the best way to delete something, preferably without having to write in a lot of code.

In my project, I mimic chemical compounds - I have instances Elementassociated with other instances Elementusing the instance Bond. In chemistry, bonds often break, and I would like to have a clean way to do it. My current method is as follows

# 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

I want to do something like

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

Alternatively, something like this would be fine

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

Is there any of these ways to make this preferable to others, or is there any other way to do this that I skip?

+4
2

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% , , , .

+5

. , del self in Bond.breakBond ( ). - , , (- Bond and Elements, __del__ , Python 3.4, ).

del name name, __del__ . , , , , name () .

:

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 
+1

Source: https://habr.com/ru/post/1526829/


All Articles