gpt4 book ai didi

Python-UnboundLocalError : local variable 'obj' referenced before assignment

转载 作者:行者123 更新时间:2023-11-28 22:42:37 24 4
gpt4 key购买 nike

我必须定义一个类方法,用于删除该类的实例。代码的框架如下:

class baseClass(object):

def __init__(self):
pass

def fun(self):
print 'Base Class'


class derivedClass(baseClass):

def __init__(self):
super(derivedClass, self).__init__()

def fun(self):
print 'Derived class'

def exitfun(self):
print 'Delete Object Instance'
del obj

obj = derivedClass()
obj.fun()
obj.exitfun()

我收到以下错误:

Traceback (most recent call last):
File "C:\Python27\inheritance_del_instance.py", line 23, in <module>
obj.exitfun()
File "C:\Python27\inheritance_del_instance.py", line 19, in exitfun
del obj
UnboundLocalError: local variable 'obj' referenced before assignment

除了打电话,

del <object> 

在 Main 中,是否有另一种方法可以通过其成员函数删除类的实例。提前致谢!

最佳答案

Python 有一个垃圾收集器,因此当没有更多引用指向它时,该对象将从内存中删除。关键字 del 只是删除变量名和对象之间的绑定(bind)(引用)。如果不再有对该对象的引用,则其内存将由垃圾收集器释放。使用 del 删除对象内部的对象是没有意义的,因为 del 本身不会触发任何删除操作。

此外,在您的代码中存在语法错误,实际上 undefined variable obj。您应该使用 self 从对象内部引用对象本身。

关于Python-UnboundLocalError : local variable 'obj' referenced before assignment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31511789/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com