MadhuraShree V N
MadhuraShree V N

Reputation: 130

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

I have to define a class method, that deletes the instance of that class. Skeleton of the code is as given below:

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()

I'm getting the following error:

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

Other than calling,

del <object> 

in Main, is there an alternate method to delete the instance of a class, by its member function. Thanks in Advance!

Upvotes: 2

Views: 2573

Answers (2)

Vincent
Vincent

Reputation: 13415

Using the keyword global would solve your issue:

def exitfun(self):
    global obj
    del obj

However, it is probably not what you want to do. In order to define a class method, you need the classmethod decorator. Also, you could save the instance at class level so you don't have to access it through the globals:

class Test(object):

    def __init__(self):
        type(self).instance = self

    def say_hello(self):
        print 'Hello!'

    @classmethod
    def remove_instance(cls):
        del cls.instance

Test()
Test.instance.say_hello()
Test.remove_instance()

Upvotes: 1

enrico.bacis
enrico.bacis

Reputation: 31514

Python has a garbage collector, so an object is removed from memory when there are no more references pointing to it. The keyword del simply removes the binding (reference) between a variable name and the object. If there are no more references to the object, its memory is freed by the garbage collector. It makes no sense to use del to delete the object inside the object since del does not trigger any deletion per se.

Moreover in your code you have a syntax error, in fact the variable obj is not defined. You should use self to reference the object itself from within it.

Upvotes: 3

Related Questions