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

Posted by Mridang Agarwalla on Stack Overflow See other posts from Stack Overflow or by Mridang Agarwalla
Published on 2010-06-14T06:17:29Z Indexed on 2010/06/14 6:22 UTC
Read the original article Hit count: 219

Filed under:

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.

© Stack Overflow or respective owner

Related posts about python