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:

  1. Anonymous17/3/09 09:58

    What does "pass" mean?

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

    ReplyDelete
  3. Anonymous17/3/09 17:25

    Yuck (the pass)

    ReplyDelete
  4. Anonymous29/9/11 01:52

    This was very helpful! Thanks :)

    ReplyDelete