If it won't be simple, it simply won't be. [Hire me, source code] by Miki Tebeka, CEO, 353Solutions

Tuesday, March 17, 2009

__subclasses__

New style classes have a __subclasses__ method which I find useful the problem of "find me all instances to run" - without any metaclass black voodoo :)

A trivial example:
#!/usr/bin/env python

class Animal(object):
pass

class Dog(Animal):
def talk(self):
return "whoof whoof"

class Cat(Animal):
def talk(self):
return "miao"

class Pig(Animal):
def talk(self):
return "oink oink"

def all_animals():
return Animal.__subclasses__()

if __name__ == "__main__":
for animal in all_animals():
print "%s says: %s" % (animal.__name__, animal().talk())


This way, if we add a new animal all_animals will work without any change from us.

4 comments:

Anonymous said...

What does "pass" mean?

Miki Tebeka said...

http://docs.python.org/tutorial/controlflow.html#pass-statements

Anonymous said...

Yuck (the pass)

Anonymous said...

This was very helpful! Thanks :)

Blog Archive