Simple prototyping in Python
Dave Benjamin
ramen at lackingtalent.com
Fri Apr 30 17:55:57 EDT 2004
In article <1095h4vc89hmcf at corp.supernews.com>, Michael Geary wrote:
> As with any other object, you can put functions as well as data in an object
> literal, e.g.:
>
> var o =
> {
> a: 5,
> incr: function() { return ++this.a },
> }
>
> o.incr() will return 6, 7, 8, etc. if you call it repeatedly.
Hey, I never knew that "this" could be used inside of an anonymous object
in JavaScript. Thanks for pointing that out!
In Python, you'd have to give the object a name, since there's no "self" to
refer to. For instance (using the "obj" and "do" functions I defined earlier):
def f():
o = obj(a=5, incr=lambda: do(o.set('a', o.a + 1), o.a))
return o
>>> o = f()
>>> o.a
5
>>> o.incr()
6
>>> o.incr()
7
Not exactly elegant, but not totally atrocious either...
--
.:[ 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