问题描述
嗨,我正在尝试破坏if语句(在一会儿之内)的条件的类对象
global variablecheck
class createobject:
def __init__(self,userinput):
self.userinput = input
self.method()
def method(self):
while True:
if self.userinput == variablecheck
print('the object created using this class is still alive')
else:
print('user object created using class(createobject) is dead')
#what code can i put here to delete the object of this class?
解决方法
这样想:您要一个类使用内部方法自毁,这就像尝试吃自己的嘴一样。
幸运的是,Python具有垃圾回收功能,这意味着一旦所有引用超出范围,您的类就会被自动销毁。
如果在销毁实例时需要做一些特定的事情,您仍然可以覆盖__del__()
,它会 kinda 充当析构函数。这是一个愚蠢的例子:
class SelfDestruct:
def __init__(self):
print("Hi! I'm being instanciated!")
def __del__(self):
print("I'm being automatically destroyed. Goodbye!")
def do_stuff(self):
print("I'm doing some stuff...")
现在,尝试在本地范围(例如函数)中实例化此类:
def make_a_suicidal_class():
my_suicidal_class = SelfDestruct()
for i in range(5):
my_suicidal_class.do_stuff()
return None
在此,对象的寿命受功能约束。这意味着一旦通话结束,它将被自动销毁。因此输出应如下所示:
>>> make_suicidal_class()
"Hi! I'm being instanciated!"
"I'm doing some stuff..."
"I'm doing some stuff..."
"I'm doing some stuff..."
"I'm doing some stuff..."
"I'm doing some stuff..."
"I'm being automatically destroyed. Goodbye!"
>>>
如果您的类是在全局范围内实例化的,那么直到您的程序结束,它才会被销毁。
此外,应注意,手动调用__del__()
析构函数实际上并不会销毁该对象。这样做:
foo = SelfDestruct()
foo.__del__()
foo.do_stuff()
结果是这样的输出:
"Hi! I'm being instanciated!"
"I'm being automatically destroyed. Goodbye!"
"I'm doing some stuff..."
ergo ,该实例仍然有脉冲...如果确实需要防止在当前范围内再次引用该实例,则必须调用del foo
来执行此操作
尽管如前所述,Python实际上引用计数类和变量。因此,如果其他情况下使用了您的类对象,则调用del foo
实际上不会从内存中释放它。
这是python文档中的详尽解释 https://docs.python.org/2.5/ref/customization.html
“ del x”不会直接调用x。 del ()-前者将x的引用计数减一,而后者仅在x的引用计数达到零时才调用。
长话短说:不要考虑!让python处理内存管理。垃圾回收的全部目的是不再担心变量的寿命!