classVar.py

class C:
 """
 A class to demonstrate class variables in Python

 Objects of class C have one private object attribute __data.
 All objects of class C share the same class variable C.instances
 which keeps track of the total number of instances made of C.
 """

 # a class variable, referred to as C.instances
 instances=0

 def __init__(self, value=0):
  """ Constructor """
  C.instances +=1
  self.setValue(value)

 def getInstances(self):
  """ getInstances() -> int
     return the number of instances made of C
  """
  return C.instances

 def setValue(self, value):
  """ setValue(value:anyType)
      Set the "value" of the C instance in the private variable __data.
      Note how ALL write access to __data is done through setValue(),
      even in __init__ !
  """ 
  self.__data=value

 def getValue(self):
  """ getValue() -> anyType
      Get the "value" of this instance found in the private variable
      __data. Note how ALL read access to __data should be through
      getValue() !
  """
  return self.__data

 def __str__(self):
  """ __str__() -> String
      Returns the string representation of the object.
      __str__(obj)  will be called by "print obj" .
  """
  return "Instance of class C, value = "+`self.getValue()`

if __name__ == '__main__':
 c1=C()
 c1
 c2=C()
 c2
 c1.getInstances()
 c2.getInstances()
 c1.setValue(10)
 c1.getValue()
 str(c1)
 c2.setValue(20)
 c2.getValue()
 str(c2)



Generated by GNU enscript 1.6.1.