How can I increase counter properties of class when a instance is called?

前端 未结 2 2035
余生分开走
余生分开走 2021-01-20 13:02

There is simple class:

class A(object):

    __COUNTER = 0

    def do_something_1(self):
        ...

    def do_something_2(self):
        ...         


        
2条回答
  •  不思量自难忘°
    2021-01-20 13:31

    Here's the simple version: How to increment a class-wide counter every time a particular function is called. The function can be __init__, which covers your specific question.

    class cls(object):
        counter = 0
    
        def __init__(self):
            self.__class__.counter += 1
            print self.__class__.counter
    
    a = cls()  # Prints 1
    b = cls()  # Prints 2
    

    As you can see, the trick is to increment self.__class__.counter, not self.counter. You can do that inside any member function.

    But don't use names starting with a double underscore, because they have special meaning for python (unless you know and want the special meaning, of course). If you want to flag the counter as private, use a single underscore: _counter.

提交回复
热议问题