« March 16, 2004 | Main | March 18, 2004 »

March 17, 2004 Archives

March 17, 2004

A failed attempt at prototyping


I noticed a discussion on rec.arts.int-fiction about using Python for writing text adventures. In text adventures, usually every single object is unique, so it's a minor irritation that you have to write classes and then instantiate the class. It would be better if you could automatically instantiate each class.


The code below comes irritatingly close to implementing this without actually doing so:


 class Prototype (type):     def __init__ (metacls, name, bases, attributes):         super(Prototype, metacls).__init__(name, bases, attributes)      def __new__ (metacls, name, bases, attributes):         klass = super(Prototype, metacls).__new__(metacls, name, bases,                                                   attributes)         inst = klass()         return inst  __metaclass__ = Prototype  class Room:     d = 3      def describe (self):         print 'I am a room.  There are %i kittens here.' % self.d  class SpecialRoom (type(Room)):     d = 4  print Room, type(Room), Room.d Room.describe() print SpecialRoom, type(SpecialRoom), SpecialRoom.d SpecialRoom.describe() 

When you run it, you get this output:


 <__main__.Room object at 0x449550> <class '__main__.Room'> 3 I am a room.  There are 3 kittens here. <__main__.SpecialRoom object at 0x449790> <class '__main__.SpecialRoom'> 4 I am a room.  There are 4 kittens here. 

But note that SpecialRoom doesn't subclass Room conventionally; you have to write class SpecialRoom (type(Room)), because then Python will look up the metaclass of the anonymous class of which Room is an instance, finding Prototype, and create a new subclass. I struggled for 45 minutes this evening trying to figure out a way around this, but failed. isinstance() doesn't work correctly, either, because Room isn't a class.


I couldn't find any other implementations of this. Ian Bicking wrote about Self-style classes, but couldn't make inheritance work either. The ASPN cookbook includes a recipe for singleton classes, but that didn't have anything relevant. Maybe I'll study Guido's tutorial some more and rethink.

About March 2004

This page contains all entries posted to AMK's Journal in March 2004. They are listed from oldest to newest.

March 16, 2004 is the previous archive.

March 18, 2004 is the next archive.

Many more can be found on the main index page or by looking through the archives.

Powered by
Movable Type 3.31