Mridang Agarwalla
Mridang Agarwalla

Reputation: 44978

How to return a value when destroying/cleaning-up an object instance

When I initiate a class in Python, I give it some values. I then call method in the class which does something. Here's a snippet:

class TestClass():
    def __init__(self):
       self.counter = 0

    def doSomething(self):
        self.counter = self.counter + 1
        print 'Hiya'

if __name__ == "__main__":
    obj = TestClass()
    obj.doSomething()
    obj.doSomething()
    obj.doSomething()
    print obj.counter

As you can see, everytime I call the doSomething method, it prints some text and increments an internal variable i.e. counter. When I initiate the class, i set the counter variable to 0. When I destroy the object, I'd like to return the internal counter variable. What would be a good way of doing this? I wanted to know if there were other ways apart from doing stuff like:

Thanks.

Upvotes: 1

Views: 170

Answers (1)

Yann Ramin
Yann Ramin

Reputation: 33177

Doing actions upon object destruction is generally frowned upon. Python offers a __del__ function, but it may not be called in certain instances.

If you were to do something with the counter variable, what would it be? Where would the data go?

Upvotes: 2

Related Questions