Created
January 28, 2013 00:15
-
-
Save mtomwing/4651589 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Author
mtomwing
commented
Jan 28, 2013
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment