Static class variable in Python

Post date: Aug 29, 2012 4:21:47 PM

If I want to keep tracking on how many times a particular class is instantiated, what should I do?

In Java we use the keyword "static" in a class to say the variable is an attribute of a class not of an object so that the variable will be shared among all objects instantiated from the class.

How would we do the same for Python? Here is the code snippet followed by the explanation.

class Node:
    cnt = 0
    def __init__(self,data=0,next=None):
        self.__class__.cnt = self.__class__.cnt + 1
        self.data = data
        self.next = next
        
    def __str__(self):
        return str(self.data)    
        
# ===== Test routine =======         
n1 = Node(1)
print n1, Node.cnt
n2 = Node(2)
print n2, Node.cnt
n3 = Node()
print n3, Node.cnt

the results are

1 1
2 2
0 3

we exploits 3 knowledges here:

  1. The variable cnt is the class variable (class attribute), hence will be instantiated only once when the class is imported
  2. We put the counter in the function __init__ because the function will be called every time an object is created
  3. However, we need to put the suffix __class__ after self so that the compiler would know that self.__class__ refers to the class of the object self. And, therefore self.__class__.cnt is seen as a class variable

What if we omit "__class__"? ---- That is, we have "self.cnt = self.cnt + 1"

  • Then, the Node.cnt would be 0 because self.cnt refers to the object attribute cnt, and does not refer to the class attribute cnt (as in Node.cnt).

Here is the example:

class Node:
    cnt = 0
    def __init__(self,data=0,next=None):
        self.cnt = self.cnt + 1
        self.data = data
        self.next = next
        
    def __str__(self):
        return str(self.data)    
        
# ===== Test routine =======         
n1 = Node(1)
print n1, Node.cnt, n1.cnt
n2 = Node(2)
print n2, Node.cnt, n2.cnt
n3 = Node()
print n3, Node.cnt, n3.cnt

The results are

1 0 1
2 0 1
0 0 1

Additional resources: