Prothon Prototypes vs Python Classes

Jeff Epler jepler at unpythonic.net
Sun Mar 28 10:57:37 EST 2004


I just wanted to jump on the "Python *can* do prototypes" bandwagon, and
offer my own solution.  To me, a prototype looks like a class where all
methods are classmethods.  Well, then, just fix that up in a metaclass.
The only other wrinkle I addressed was calling __init__ (because an
instance is never created).  Special methods (such as __add__, __call__)
probably don't do anything sane.

This code is distributed under the "Free to a good home" license.

Jeff


import sys, types

class PrototypeMeta(type):
    def __init__(cls, name, bases, dict):
        super(PrototypeMeta, cls).__init__(name, bases, dict)
        for name, value in dict.items():
            if isinstance(value, types.FunctionType):
                setattr(cls, name, classmethod(value))
        # cls always has __init__ -- it can either be object's init,
        # (which is a wrapper_descriptor) or a desired init (which is
        # a bound classmethod).  call it if it's the right one.
        if isinstance(cls.__init__, types.MethodType):
            cls.__init__()

    def __call__(
__metaclass__ = PrototypeMeta

class Thing:
    name = "Unnamed Thing"
    desc = "(Undescribed thing)"
    def __init__(self):
        print "created a new thing:", self.name

    def look(self):
        print "You see a", self.name
        print self.desc

class Room:
    name = "Unnamed Room"
    desc = "(Undescribed room)"
    contents = []

    def look(self):
        print "You are in", self.name
        print
        print self.desc
        print
        if self.contents:
            print "Things here:"
            for c in self.contents:
                print c.name
            print

class Python(Thing):
    name = "a snake"
    desc = "This snake has the number '%s' written on its belly" \
            % sys.version.split()[0]

class LivingRoom(Room):
    name = "Living Room"
    desc = """There is a large window on the south side of the room, which 
is also the location of the door to the outside.  On the west wall is an
unused fireplace with plants on the mantle.  A hallway is to the west,
and the dining room is north."""
    contents = [Python]

class DarkRoom(Room):
    def look(self):
        print "Where am I?  It's dark in here!"
        print

print
LivingRoom.look()
DarkRoom.look()
Python.look()




More information about the Python-list mailing list