Skip to content

Instantly share code, notes, and snippets.

@mtomwing
Last active December 11, 2015 19:49
Show Gist options
  • Save mtomwing/4651348 to your computer and use it in GitHub Desktop.
Save mtomwing/4651348 to your computer and use it in GitHub Desktop.
from collections import defaultdict
class Dog(object):
__instance_count = defaultdict(int)
def __init__(self):
self.__instance_count[self.__class__.__name__] += 1
def __del__(self):
self.__instance_count[self.__class__.__name__] -= 1
@classmethod
def count(cls):
return cls.__instance_count[cls.__name__]
class Puppy(Dog):
pass
if __name__ == '__main__':
dog = Dog()
pup = Puppy()
print 'Dog:', dog.count()
print 'Pup:', pup.count()
del pup
print 'Dog:', Dog.count()
print 'Pup:', Puppy.count()
@mtomwing
Copy link
Author

thinkpad[~/Projects/ark] python2 test.py 
Dog: 1
Pup: 1
Dog: 1
Pup: 0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment