Simple prototyping in Python

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Dave Benjamin

    Simple prototyping in Python

    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__.u pdate(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. :
  • has

    #2
    Re: Simple prototyping in Python

    Dave Benjamin <ramen@lackingt alent.com> wrote in message news:<slrnc938v m.1v0.ramen@lac kingtalent.com> ...[color=blue]
    > 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.[/color]

    It doesn't even do that; at least not in the sense that class-based OO
    defines it, where inheritance merely describes the initial state for
    every object created from a class.

    To me, the way Prothon and Io do "prototypes " feels more like a leaky
    abstraction, where a common internal optimisation for proto-OO systems
    has somehow leaked out into user-space. See if I ever find that
    Lieberman fellow, think I'll be having a word or two with 'im. ;)

    [color=blue]
    > 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.[/color]

    In a proto-OO system all objects are _completely_ anonymous*, having
    no 'class' and all being of the same type, 'object'. In this respect,
    they're just like strings, lists, dicts, or any other 'anonymous'
    type; a list is a list is a list, for example, regardless of how it is
    used.


    (* To the user, anyway. Of course, they still have internal ids so the
    runtime can track 'em, but that's not something the user ever needs to
    know about.)
    [color=blue]
    > JavaScript has a syntax
    > for this:
    >
    > var o = {a: 5, b: 6}[/color]

    Looks on the surface like AppleScript's record type, which is roughly
    analogous to C structs... and useless for anything more than
    struct-style usage. While I did read about JS programming in the
    dim-n-distant past - it was one of a number of languages I looked at
    when learning proto-OO on AS, which lacked any decent learning
    material on the topic - I've pretty much forgotten everything since.
    So can I ask: is the JS structure more flexible; e.g. can one add
    functions to it to operate like methods on the other data in the
    structure? Or does it have to provide a second structure for proto-OO
    use, as AS does?

    Comment

    • Dave Benjamin

      #3
      Re: Simple prototyping in Python

      In article <69cbbef2.04043 00855.20dd436b@ posting.google. com>, has wrote:[color=blue]
      > Dave Benjamin <ramen@lackingt alent.com> wrote in message news:<slrnc938v m.1v0.ramen@lac kingtalent.com> ...[color=green]
      >> 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.[/color]
      >
      > It doesn't even do that; at least not in the sense that class-based OO
      > defines it, where inheritance merely describes the initial state for
      > every object created from a class.[/color]

      But that is how it is used, anyway. See any textbook describing OO
      programming in JavaScript. The caveats are also typically described, and
      other hacks like the "__proto__" attribute (which is the object's prototype
      object, not to be confused with the constructor's prototype object,
      "prototype" ) are used to exercise more control (or confusion) over the matter.
      [color=blue]
      > In a proto-OO system all objects are _completely_ anonymous*, having
      > no 'class' and all being of the same type, 'object'. In this respect,
      > they're just like strings, lists, dicts, or any other 'anonymous'
      > type; a list is a list is a list, for example, regardless of how it is
      > used.[/color]

      Not necessarily. In JavaScript, you can still do "instanceof ", for example.
      [color=blue][color=green]
      >> JavaScript has a syntax
      >> for this:
      >>
      >> var o = {a: 5, b: 6}[/color]
      >
      > Looks on the surface like AppleScript's record type, which is roughly
      > analogous to C structs... and useless for anything more than
      > struct-style usage. While I did read about JS programming in the
      > dim-n-distant past - it was one of a number of languages I looked at
      > when learning proto-OO on AS, which lacked any decent learning
      > material on the topic - I've pretty much forgotten everything since.
      > So can I ask: is the JS structure more flexible; e.g. can one add
      > functions to it to operate like methods on the other data in the
      > structure? Or does it have to provide a second structure for proto-OO
      > use, as AS does?[/color]

      Sure! JavaScript supports function literals that are true closures. In fact,
      this feature can be used to support private data, which has been described
      in some detail by Douglas Crockford, here:



      The same technique can be accomplished by Python, though it'd be really nice
      to have code blocks or function literals that accept statements.

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

      Comment

      • Michael Geary

        #4
        Re: Simple prototyping in Python

        > Dave Benjamin wrote:[color=blue][color=green]
        > > JavaScript has a syntax for this:
        > >
        > > var o = {a: 5, b: 6}[/color][/color]

        has wrote:[color=blue]
        > Looks on the surface like AppleScript's record type, which
        > is roughly analogous to C structs... and useless for anything
        > more than struct-style usage. While I did read about JS
        > programming in the dim-n-distant past - it was one of a
        > number of languages I looked at when learning proto-OO
        > on AS, which lacked any decent learning material on the
        > topic - I've pretty much forgotten everything since. So can
        > I ask: is the JS structure more flexible; e.g. can one add
        > functions to it to operate like methods on the other data in
        > the structure? Or does it have to provide a second structure
        > for proto-OO use, as AS does?[/color]

        A JavaScript object literal is simply a convenient way to construct an
        object. You can put anything in that object that you can put in any other
        object.

        This object literal:

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

        is just a shorthand for:

        var o = new Object
        o.a = 5
        o.b = 6

        In fact, if you do o.toSource() after either of those, you'll get the same
        result:

        ({a:5, b:6})

        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.

        As Dave mentioned, you can also use closures, as in this example which uses
        both a closure and a property in the object literal:

        function F()
        {
        var c = 105;

        return {
        a: 5,
        incr: function() { return [ ++this.a, ++c ] },
        }
        }

        var x = new F
        var y = new F
        x.incr()
        y.incr()

        -Mike


        Comment

        • Dave Benjamin

          #5
          Re: Simple prototyping in Python

          In article <1095h4vc89hmcf @corp.supernews .com>, Michael Geary wrote:[color=blue]
          > 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.[/color]

          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
          [color=blue][color=green][color=darkred]
          >>> o = f()
          >>> o.a[/color][/color][/color]
          5[color=blue][color=green][color=darkred]
          >>> o.incr()[/color][/color][/color]
          6[color=blue][color=green][color=darkred]
          >>> o.incr()[/color][/color][/color]
          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. :

          Comment

          Working...