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:
cnt
is the class variable (class attribute), hence will be instantiated only once when the class is imported__init__
because the function will be called every time an object is created__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 variableNode.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: