Skip to content

Instantly share code, notes, and snippets.

@mtomwing
Created January 28, 2013 00:15
Show Gist options
  • Save mtomwing/4651589 to your computer and use it in GitHub Desktop.
Save mtomwing/4651589 to your computer and use it in GitHub Desktop.
from collections import defaultdict
class Dog(object):
__instance_count = defaultdict(int)
def __init__(self, colour='white', breed='mutt'):
self.colour = colour
self.breed = breed
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__]
@classmethod
def count_all(cls):
return sum(cls.__instance_count.values())
# Override these
def speak(self):
print 'wuf wuf'
def __repr__(self):
return 'this Dog is a %s %s' % (self.colour, self.beed)
class Puppy(Dog):
def __init__(self, colour='white', breed='mutt', wormed=True):
super(Puppy, self).__init__(colour, breed)
self.wormed = wormed
def speak(self):
print 'ruf'
def __repr__(self):
worm_status = self.wormed and 'is dewormed' or 'might have worms'
return 'this Puppy is a %s %s and %s' % (
self.colour,
self.breed,
worm_status,
)
if __name__ == '__main__':
dog = Dog()
pup = Puppy()
print 'Dog:', dog.count()
print 'Pup:', pup.count()
print 'All:', Dog.count_all()
del pup
print 'Dog:', Dog.count()
print 'Pup:', Puppy.count()
print 'All:', Dog.count_all()
@mtomwing
Copy link
Author

thinkpad[~/Projects/ark] python2 count_instances.py 
Dog: 1
Pup: 1
All: 2
Dog: 1
Pup: 0
All: 1

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