tags:

views:

42

answers:

1

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.

+2  A: 

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?

Yann Ramin
You're right. I did some reading. It is bad practice.
Mridang Agarwalla