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:
- The variable
cnt
is the class variable (class attribute), hence will be instantiated only once when the class is imported - We put the counter in the function
__init__
because the function will be called every time an object is created - However, we need to put the suffix
__class__
afterself
so that the compiler would know thatself.__class__
refers to the class of the objectself
. And, thereforeself.__class__.cnt
is seen as a class variable
What if we omit "__class__"? ---- That is, we have "self.cnt = self.cnt + 1"
What if we omit "__class__"? ---- That is, we have "self.cnt = self.cnt + 1"
- Then, the
Node.cnt
would be 0 becauseself.cnt
refers to the object attributecnt
, and does not refer to the class attributecnt
(as inNode.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:
- "Dive into Python" -- Example 5.8 Modifying Class Attributes