Python中的自定义析构函数 [英] Custom destructor in Python
问题描述
class Container():
def __init __(self,name) :
self.name =名称
class Data():
def __init __(self):
self._containers = []
def add_container(self,name):
self._containers.append(name)
setattr(self,name,Container(name))
现在让我们说
myData = Data()
myData.add_container('contA')
现在,如果我执行 del myData.contA
,它当然不会从 myData._containers
中删除名称
。 / p>
那么我将如何在 Container
中编写一个析构函数,以便它删除属性但也从<$ c中删除名称$ c> _containers 列表?
您似乎习惯了确定性对象销毁的语言以及执行该破坏的专用方法。 Python不能那样工作。 Python没有析构函数,即使它具有析构函数,也无法保证 del myData.contA
将使Container对象有资格被销毁,更不用说实际销毁它了。 / p>
可能最简单的方法是定义 remove_container
与 add_container $ c平行$ c>:
def remove_container(self,name):
self._containers.remove(name)
delattr(self,name)
如果您确实希望此操作的语法为 del myData.contA
,然后通过对 Data $实施
__ delattr __
插入属性删除c $ c>:
def __delattr __(self,name):
self._containers.remove(name)
super().__ delattr __(名称)
Let's say I have two classes:
class Container():
def __init__(self, name):
self.name = name
class Data():
def __init__(self):
self._containers = []
def add_container(self,name):
self._containers.append(name)
setattr(self, name, Container(name))
Now let's say
myData = Data()
myData.add_container('contA')
Now, if I do del myData.contA
it of course doesn't remove name
from myData._containers
.
So how would I write a destructor in Container
so it deletes the attribute but also removes name from the _containers
list?
You seem to be used to a language with deterministic object destruction and dedicated methods for performing that destruction. Python doesn't work that way. Python has no destructors, and even if it had destructors, there is no guarantee that del myData.contA
would render the Container object eligible for destruction, let alone actually destroy it.
Probably the simplest way is to just define a remove_container
paralleling your add_container
:
def remove_container(self, name):
self._containers.remove(name)
delattr(self, name)
If you really want the syntax for this operation to be del myData.contA
, then hook into attribute deletion, by implementing a __delattr__
on Data
:
def __delattr__(self, name):
self._containers.remove(name)
super().__delattr__(name)
这篇关于Python中的自定义析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!