How to return a value when destroying/cleaning-up an object instance
- by Mridang Agarwalla
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:
accessing the variable directly. Like obj.counter.
creating a method like getCounter.
Thanks.