Javascript uses a prototype model for its objects. However, the language is very flexible and easy to write in a few lines, which replace a different view of the structure. For example, you can create a class function that emulates the behavior of a standard class, including inheritance or private members. Or you can use flexible functional tools by writing, for example, a curry function that takes a function and some of its arguments and returns a partially applied function.
I was wondering if it is possible to do the opposite and imitate the prototype method in more classical languages. In particular, I thought a bit about whether prototypes can be simulated in Python, but the lack of support for anonymous functions (more general than lambdas) leaves me stuck.
Can I write some functions to simulate propotypes in class-based languages, in particular in Python?
EDIT Let me give an example of how such a thing could be implemented (but I really am not able to do all this).
First, what closely resembles Javascript objects is the Python dictionary. So we could have simple objects like
foo = { 'bar': 1, 'foobar': 2 }
Of course, we want to add a method, and that is not a problem if the method is placed in lambda
foo = { 'bar': 1, 'foobar': 2, 'method': lambda x: x**2 }
So now we can call the instance
foo['method'](2) >>> 4
Now , if , we had arbitrary functions like methods, which we could continue like this. First, we need functions inside foo to have access to foo itself; otherwise, these are ordinary functions, not methods.
I assume that this can be done by applying the makeObject function to foo , which goes through the values โโof foo and, when it finds the value to be called, changes its __call__ attribute to pass foo as its first argument.
At this stage, we would have independent objects that can be declared without the need to create classes.
Then we need to provide a prototype foo , which can be passed as the second argument to the makeObject function. The function should change foo.__getattr__ and foo.__setattr__ as follows: whenever an attribute is not found in foo , it should be searched in foo.prototype .
So, I think I can implement this, expect one thing: I cannot think of how to declare methods more complex than lambdas, except that they declared them in advance and bound them to my object. The problem is the lack of anonymous functions. I asked here because maybe some Python guru might have found some clever way around this.