Advertisement
cwchen

Derived class' class variable demo in Python

Feb 10th, 2016
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.18 KB | None | 0 0
  1. class Person(object):
  2.     count = 0
  3.  
  4.     def __init__(self, name, age):
  5.         klass = globals()[self.__class__.__name__]
  6.         self.name = name
  7.         self.age = age
  8.         klass.count += 1
  9.  
  10.     def __del__(self):
  11.         klass = globals()[self.__class__.__name__]
  12.         klass.count -= 1
  13.  
  14.     @classmethod
  15.     def get_count(cls):
  16.         return cls.count
  17.  
  18. class Student(Person):
  19.     def __init__(self, name, age):
  20.         klass = globals()[self.__class__.__name__]
  21.         super(klass, self).__init__(name, age)
  22.         for base in self.__class__.__bases__:
  23.             parent = globals()[base.__name__]
  24.             parent.count += 1
  25.  
  26.     def __del__(self):
  27.         klass = globals()[self.__class__.__name__]
  28.         super(klass, self).__del__()
  29.         for base in self.__class__.__bases__:
  30.             parent = globals()[base.__name__]
  31.             parent.count -= 1
  32.  
  33. if __name__ == '__main__':
  34.     a = Student('Michael', 35)
  35.     b = Person('Gladys', 52)
  36.     c = Student('Susan', 26)
  37.  
  38.     print 'person:', Person.get_count()
  39.     print 'student:', Student.get_count()
  40.  
  41.     del c
  42.     print 'person:', Person.get_count()
  43.     print 'student:', Student.get_count()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement