473,756 Members | 6,106 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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. :
Jul 18 '05 #1
4 1227
has
Dave Benjamin <ra***@lackingt alent.com> wrote in message news:<slrnc938v m.1v0.ra***@lac kingtalent.com> ...
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.
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. ;)

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.
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.)
JavaScript has a syntax
for this:

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


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?
Jul 18 '05 #2
In article <69************ **************@ posting.google. com>, has wrote:
Dave Benjamin <ra***@lackingt alent.com> wrote in message news:<slrnc938v m.1v0.ra***@lac kingtalent.com> ...
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.
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.


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.
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.


Not necessarily. In JavaScript, you can still do "instanceof ", for example.
JavaScript has a syntax
for this:

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


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?


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:

http://www.crockford.com/javascript/private.html

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. :
Jul 18 '05 #3
> Dave Benjamin wrote:
JavaScript has a syntax for this:

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

has wrote: 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?


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
Jul 18 '05 #4
In article <10************ @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. :
Jul 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

30
2774
by: Dave Allison | last post by:
Oh no, not another "check out my cool new language" posting :-) For about 5 years now, I have been developing a scripting/prototyping language that is now available on the net. It's called Aikido and was born in Sun Labs, but has been released as open source. I no longer work for Sun, but am continuing to use and develop it. The language has a syntax similar to C++ and Java but is aimed at adhoc and prototyping tasks. Unlike other...
9
2677
by: Carl | last post by:
I have been using Python for quite some time now and I love it. I use it mainly for explorative computing and numerical prototyping, ie testing and trying out different kinds of algorithms and computational schemes. The use of Python as my first-choice language has made me extremely productive. Now, I have always believed that Python is a poor performer in terms of numerical speed. My experience, however, is that the efficient use of...
1
1813
by: cainlevy | last post by:
Hey all, What are the pros and cons of defining methods in the constructor vs through the prototype? For example: Constructing: ------------- function MyObj() { this.MyMethod = function() {};
4
2227
by: Tilted | last post by:
Does anyone here use prototyping tools? I'm building one myself as I feel like I'm doing the same thing over and over again with the majority of my projects, how do people generally feel about them? Do people ever use the generated code in production? Thoughts appreciated. Chris.
10
2139
by: Burton Samograd | last post by:
Hi, Is there any way to 'prototype' functions in python, as you would in C? Would that be what the 'global' keyword is for, or is there a more elegant or 'pythonic' way of doing forward references? -- burton samograd kruhft .at. gmail kruhft.blogspot.com www.myspace.com/kruhft metashell.blogspot.com
1
1680
by: matt.rasmus | last post by:
I have been using python for the last two years to create various visualizations for my research in computational biology. Over the years, I found that I often needed the same kinds of features for many of my visualizations (OpenGL graphics with basic scrolling and zooming). I have implemented these features in an extension module for python called SUMMON which I have made freely available on my website for anyone who is interested...
176
8424
by: nw | last post by:
Hi, I previously asked for suggestions on teaching testing in C++. Based on some of the replies I received I decided that best way to proceed would be to teach the students how they might write their own unit test framework, and then in a lab session see if I can get them to write their own. To give them an example I've created the following UTF class (with a simple test program following). I would welcome and suggestions on how anybody...
10
4198
by: erokar | last post by:
Which tools would you use? I want the interface design to be as easy and fast as possible, all ideology aside. I'm considering either IronPython+Visual Studio or Python+Qt -- but I'm open for other suggestions. Visual Studio seems to offer the easiest solution, but is IronPython stable enough? How easy is the IronPython/Visual Studi integration? What about IronPython Studio?
0
879
by: Victor Bay | last post by:
Hi, pythoners, I am planning a face-to-face meetup on RAD with python: http://python.meetup.com/190/ Depends on the time commitment frame of python developers, we meet monthly, weekly, or even daily, at convenient place like coffee society, library, bookstore, ..., etc. I will also be trying to keep a concurrent blogs -- in text, pictures, videos -- to keep track of activities and topics as much as possible.
0
9271
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10028
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9836
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8709
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7242
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5139
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5301
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3352
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2664
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.