Simple prototyping in Python

Dave Benjamin ramen at lackingtalent.com
Thu Apr 29 20:43:56 EDT 2004


The recent conversation on prototype-based OOP and the Prothon project has
been interesting. I've been playing around with the idea for awhile now,
actually, since I do a lot of programming in JavaScript/ActionScript. I feel
like people are focusing too much on the "prototype chain", which to me is
mainly an attempt at reintroducing inheritance. I almost never use
inheritance anymore, preferring delegation instead in most cases. What I
think is much more interesting about the prototype-based style is the
ability to create and pass around anonymous objects. JavaScript has a syntax
for this:

var o = {a: 5, b: 6}

which is roughly equivalent to Python's:

class Whatever: pass
o = Whatever()
o.a = 5
o.b = 6

If you can tolerate some Lispism, you can actually create anonymous objects
in straight Python. This is liable to get some adverse reactions, but I just
want to demonstrate that it *can* be done. Here's an example:

class obj:
    def __init__(self, **kwds):
        self.__dict__.update(kwds)
            
    def set(self, name, value):
        setattr(self, name, value)
                        
def do(*args):
    return args[-1]
                            
def counter(start):
    ref = obj(value=start)
    return obj(
        current = lambda: ref.value,
        next    = lambda: do(
            ref.set('value', ref.value + 1),
            ref.value))
            
c = counter(0)
print c.current()
print c.next()
print c.next()
print c.current()

This outputs:

0
1
2
2

-- 
.:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:.
:  please talk to your son or daughter about parametric polymorphism. :



More information about the Python-list mailing list