Ruby Method Lookup (comparison with JavaScript) - javascript

I want to better understand how objects in Ruby have access methods defined in classes and modules. Specifically, I want to compare and contrast it with JavaScript (which I'm more familiar with).
In JavaScript, objects look up methods on the object itself and if it can't find it there, it'll look for the method on the prototype object. This process will continue until reaching Object.prototype.
// JavaScript Example
var parent = {
someMethod: function () {
console.log( 'Inside Parent' );
}
};
var child = Object.create( parent );
child.someMethod = function () {
console.log( 'Inside Child' );
};
var obj1 = Object.create( child );
var obj2 = Object.create( child );
obj1.someMethod(); // 'Inside Child'
obj2.someMethod(); // 'Inside Child'
In the JavaScript example, both obj1 and obj2 don't have the someMethod function on the object itself. The key to note is that:
There's one copy of the someMethod function in the child object and both obj1 and obj2 delegate to the child object.
What this means is that neither obj nor obj2 have copies of the someMethod function on the objects themselves.
If the child object didn't have the someMethod function defined, then delegation would continue to the parent object.
Now I want to contrast this with a similar example in Ruby:
# Ruby Example
class Parent
def some_method
put 'Inside Parent'
end
end
class Child < Parent
def some_method
puts 'Inside Child'
end
end
obj1 = Child.new
obj2 = Child.new
obj1.some_method # 'Inside Child'
obj2.some_method # 'Inside Child'
Here are my questions:
Does obj1 and obj2 in the Ruby code each own a copy of the some_method method? Or is it similar to JavaScript where both objects have access to some_method via another object (in this case, via the Child class)?
Similarly, when inheritance is taken into account in Ruby, does each Ruby object have a copy of all of the class and superclass methods of the same name?
My gut tells me that Ruby objects DO NOT have separate copies of the methods inherited from their class, mixed-in modules, and superclasses. Instead, my gut is that Ruby handles method lookup similarly to JavaScript, where objects check if the object itself has the method and if not, it looks up the method in the object's class, mixed-in modules, and superclasses until the lookup reaches BasicObject.

Does obj1 and obj2 in the Ruby code each own a copy of the some_method method? Or is it similar to JavaScript where both objects have access to some_method via another object (in this case, via the Child class)?
You don't know. The Ruby Language Specification simply says "if you do this, that happens". It does, however, not prescribe a particular way of making that happen. Every Ruby implementation is free to implement it in the way it sees fit, as long as the results match those of the spec, the spec doesn't care how those results were obtained.
You can't tell. If the implementation maintains proper abstraction, it will be impossible for you to tell how they do it. That is just the nature of abstraction. (It is, in fact, pretty much the definition of abstraction.)
Similarly, when inheritance is taken into account in Ruby, does each Ruby object have a copy of all of the class and superclass methods of the same name?
Same as above.
There are a lot of Ruby implementations currently, and there have been even more in the past, in various stages of (in)completeness. Some of those implement(ed) their own object models (e.g. MRI, YARV, Rubinius, MRuby, Topaz, tinyrb, RubyGoLightly), some sit on top of an existing object model into which they are trying to fit (e.g. XRuby and JRuby on Java, Ruby.NET and IronRuby on the CLI, SmallRuby, smalltalk.rb, Alumina, and MagLev on Smalltalk, MacRuby and RubyMotion on Objective-C/Cocoa, Cardinal on Parrot, Red Sun on ActionScript/Flash, BlueRuby on SAP/ABAP, HotRuby and Opal.rb on ECMAScript)
Who is to say that all of those implementations work exactly the same?
My gut tells me that Ruby objects DO NOT have separate copies of the methods inherited from their class, mixed-in modules, and superclasses. Instead, my gut is that Ruby handles method lookup similarly to JavaScript, where objects check if the object itself has the method and if not, it looks up the method in the object's class, mixed-in modules, and superclasses until the lookup reaches BasicObject.
Despite what I wrote above, that is a reasonable assumption, and is in fact, how the implementations that I know about (MRI, YARV, Rubinius, JRuby, IronRuby, MagLev, Topaz) work.
Just think about what it would mean if it weren't so. Every instance of the String class would need to have its own copy of all of String's 116 methods. Think about how many Strings there are in a typical Ruby program!
ruby -e 'p ObjectSpace.each_object(String).count'
# => 10013
Even in this most trivial of programs, which doesn't require any libraries, and only creates one single string itself (for printing the number to the screen), there are already more than 10000 strings. Every single one of those would have its own copies of the over 100 String methods. That would be huge waste of memory.
It would also be a synchronization nightmare! Ruby allows you to monkeypatch methods at any time. What if I redefine a method in the String class? Ruby would now have to update every single copy of that method, even across different threads.
And I actually only counted public methods defined directly in String. Taking into account private methods, the number of methods is even bigger. And of course, there is inheritance: strings wouldn't just need a copy of every method in String, but also a copy of every method in Comparable, Object, Kernel, and BasicObject. Can you imagine every object in the system having a copy of require?
No, the way it works in most Ruby implementations is like this. An object has an identity, instance variables, and a class (in statically typed pseudo-Ruby):
struct Object
object_id: Id
ivars: Dictionary<Symbol, *Object>
class: *Class
end
A module has a method dictionary, a constant dictionary, and a class variable dictionary:
struct Module
methods: Dictionary<Symbol, *Method>
constants: Dictionary<Symbol, *Object>
cvars: Dictionary<Symbol, *Object>
end
A class is like a module, but it also has a superclass:
struct Class
methods: Dictionary<Symbol, *Method>
constants: Dictionary<Symbol, *Object>
cvars: Dictionary<Symbol, *Object>
superclass: *Class
end
When you call a method on an object, Ruby will look up the object's class pointer and try to find the method there. If it doesn't, it will look at the class's superclass pointer and so on, until it reaches a class which has no superclass. At that point it will actually not give up, but try to call the method_missing method on the original object, passing the name of the method you tried to call as an argument, but that's just a normal method call, too, so it follows all the same rules (except that if a call to method_missing reaches the top of the hierarchy, it will not try to call it again, that would result in an infinite loop).
Oh, but we ignored one thing: singleton methods! Every object needs to have its own method dictionary as well. Actually, rather, every object has its own private singleton class in addition to its class:
struct Object
object_id: Id
ivars: Dictionary<Symbol, *Object>
class: *Class
singleton_class: Class
end
So, method lookup starts first in the singleton class, and only then goes to the class.
And what about mixins? Oh, right, every module and class also needs a list of its included mixins:
struct Module
methods: Dictionary<Symbol, *Method>
constants: Dictionary<Symbol, *Object>
cvars: Dictionary<Symbol, *Object>
mixins: List<*Module>
end
struct Class
methods: Dictionary<Symbol, *Method>
constants: Dictionary<Symbol, *Object>
cvars: Dictionary<Symbol, *Object>
superclass: *Class
mixins: List<*Module>
end
Now, the algorithm goes: look first in the singleton class, then the class and then the superclass(es), where however, "look" also means "after you look at the method dictionary, also look at all the method dictionaries of the included mixins (and the included mixins of the included mixins, and so forth, recursively) before going up to the superclass".
Does that sound complicated? It is! And that's not good. Method lookup is the single most often executed algorithm in an object-oriented system, it needs to be simple and lightning fast. So, what some Ruby implementations (e.g. MRI, YARV) do, is to decouple the interpreter's internal notion of what "class" and "superclass" mean from the programmer's view of those same concepts.
An object no longer has both a singleton class and a class, it just has a class:
struct Object
object_id: Id
ivars: Dictionary<Symbol, *Object>
class: *Class
singleton_class: Class
end
A class no longer has a list of included mixins, just a superclass. It may, however, be hidden. Note also that the Dictionaries become pointers, you'll see why in a moment:
struct Class
methods: *Dictionary<Symbol, *Method>
constants: *Dictionary<Symbol, *Object>
cvars: *Dictionary<Symbol, *Object>
superclass: *Class
visible?: Bool
end
Now, the object's class pointer will always point to the singleton class, and the singleton class's superclass pointer will always point to the object's actual class. If you include a mixin M into a class C, Ruby will create a new invisible class M′ which shares its method, constant and cvar dictionaries with the mixin. This mixin class will become the superclass of C, and the old superclass of C will become the superclass of the mixin class:
M′ = Class.new(
methods = M->methods
constants = M->constants
cvars = M->cvars
superclass = C->superclass
visible? = false
)
C->superclass = *M'
Actually, it's little bit more involved, since it also has to create classes for the mixins that are included in M (and recursively), but in the end, what we end up with is a nice linear method lookup path with no side-stepping into singleton classes and included mixins.
Now, the method lookup algorithm is just this:
def lookup(meth, obj)
c = obj->class
until res = c->methods[meth]
c = c->superclass
raise MethodNotFound, meth if c.nil?
end
res
end
Nice and clean and lean and fast.
As a trade-off, finding out the class of an object or the superclass of a class is slightly more difficult, because you can't simply return the class or superclass pointer, you have to walk the chain until you find a class that is not hidden. But how often do you call Object#class or Class#superclass? Do you even call it at all, outside of debugging?
Unfortunately, Module#prepend doesn't fit cleanly into this picture. And Refinements really mess things up, which is why many Ruby implementations don't even implement them.

Let's continue working with your example in an IRB session and see what we might learn:
> obj1.method(:some_method)
=> #<Method: Child#some_method>
> obj1.method(:some_method).source_location
=> ["(irb)", 8]
> obj2.method(:some_method)
=> #<Method: Child#some_method>
> obj2.method(:some_method).source_location
=> ["(irb)", 8]
Ah ok, so two objects of the same class have the same Method. I wonder if that's always true...
> obj1.instance_eval do
> def some_method
> puts 'what is going on here?'
> end
> end
=> nil
> obj1.some_method
what is going on here?
=> nil
> obj2.some_method
Inside Child
=> nil
> obj1.method(:some_method)
=> #<Method: #<Child:0x2b9c128>.some_method>
> obj1.method(:some_method).source_location
=> ["(irb)", 19]
Well that's interesting.
James Coglan has a nice blog post which is offers a better explanation of much of this than I will at https://blog.jcoglan.com/2013/05/08/how-ruby-method-dispatch-works/
It might also be interesting to consider when any of this is important. Think about how much of this system is an implementation detail of the interpreter and could be handled differently in MRI, JRuby, and Rubinius and what actually needs to be consistent for a Ruby program to execute consistently in all of them.

More food for thought
> obj1.instance_eval do
> def some_method
> puts "Inside Instance"
> super
> end
> end
=> :some_method
Inside Instance
Inside Child

Related

Static method instead of Prototype method Javascript

When instance function are called in a class each instance of object get own copy of function but in prototype method and static method no copy is created , they belong to class, so if they both doesn't create a copy of their function, so why do we have static function if we can simply use prototype method if we don't want to copy??
I am a little bit confuse, if anyone can explain it will be a great help
In order to use a prototype/instance method, you need to either have an instance of an object or specifically access the type's .prototype. For methods that don't require an instance, a static method provides simpler syntax. Think of the String.fromCharCode() method as an example. It wouldn't make sense to say:
let str = "dummy string".fromCharCode(127);
The extra string instance there is just a distraction from what you're really trying to do:
let str = String.fromCharCode(127);
This applies good programming practices of reduced coupling (not requiring an instance in order to invoke a method that doesn't need it) and information hiding (by not exposing a method on instances of objects which doesn't pertain to those specific objects).
A static method does not exist on instances. Prototype methods do. So, if you want to call someArr.filter(x => x > 5) that would be an instance method that works on the given array.
An example of astatic method is Array.isArray(someArr). It makes very little sense to make the static method an instance method because you'd need an instance before calling it. That would lead to code like someArr.isArray(someArr) which is illogical - you need an array to check if something is an array. And that can very easily be fail spectacularly if someArr is not in fact an array:
const someArr = {
isArray() { return true; },
filter() { return "I am not an array"; },
};
console.log(someArr.isArray(someArr));
console.log(someArr.filter(x => x > 5));
Yes, that example is indeed highly illogical in order to highlight why it is weird. Assuming .isArray() was an instance method, you could create a new array in order to use it to call [].isArray(someArr). But that method does not require any instance data. The object created exists only to give you access to the method and is discarded immediately afterwards. That design is still not sensible.
Both static methods and prototype methods exist independent from any instances. The difference is that a prototype method expects to be called on an instance, i.e. to have an instance passed as the this argument, whereas the static method does not require an instance and expects none.
Even without placing them anywhere on the class, we can see this distinction in the following example:
function myStaticMethod(arg) {
console.log('Doing something with '+arg);
}
function myMethod(arg) {
console.log('Doing something with '+this+' and '+arg);
}
const myInstance = new MyClass();
myStaticMethod('value');
myMethod.call(myInstance, 'value');
Now the .call() syntax is not very ergonomic, we prefer myInstance.myMethod('value'), so that is why we place the method on the prototype object of the class, having it inherited by all instances.
For static methods, this is not necessary. They don't need an instance, we don't want to call them on an instance, we want to call them as MyClass.myStaticMethod('value') so that is where we place them. We could put them on the prototype as well, but that would lead to confusion (myInstance.myStaticMethod()), name collisions, and unncessarily long invocations (MyClass.prototype.myStaticMethod()). It's imaginable to write new MyClass().myStaticMethod(), but there you would unnecessarily create an instance that is not required (and it might not even be possible to create).

Role of 'prototype' property amidst design of `function` type object?

As per the understanding, The main purpose for the existence of prototype property in a function type object is to allow properties/methods sitting under prototype to get inherited by other objects. This enables prototypical inheritance.
Considering window['Number'] function type object,
In general, Idea is to understand the thought process on what comes under prototype. So. I would like to take a specific example i.e., Number, with below questions.
From design perspective, how would I understand,
1)
why parseFloat()/parseInt()/isFinite()/isInteger()/isFinite()/isNaN()/NEGATIVE_INFINITY/NaN
are part of function type object Number?
2)
why methods toExponential()/toFixed()/toPrecision() are part of Number.prototype object?
Note: Have an idea on class based inheritance using java syntax, where both static/instance members can be inherited.
If you understand classic class based inheritance, then Number.parseFloat is a static class method, while Number.prototype.toFixed is an instance method. The "class methods" do not need an instance of Number to work, you simply call them directly as Number.parseFloat(foo). Instance methods on the other hand require an instance first:
var foo = new Number(bar);
foo.toFixed();
Properties declared on the prototype object are visible from all instances. Thus:
var n1 = new Number(1), n2 = new Number(2);
Those are two instances of Number, and via each instance it's possible to call the functions on the Number prototype:
alert( n2.toExponential() ); // "2e+0"
Because of the way that function invocation works in JavaScript, the .toExponential() function in that example will be invoked with this referring to the number instance used to make the function call — n2 in this case.
Now, the .toExponential() function could have been defined as a property of the Number constructor itself, but then the parameter would have to be passed explicitly (like Number.toExponential(2)). That's not how the runtime was designed, however. As with so many "why?" questions about how languages and APIs work, it's ultimately just a design preference on the part of the language designers. It should be clear that something like .parseFloat() would really not make any sense as a prototype method, because the whole point of .parseFloat() is to turn something that's not a number into a number. (It could have been added to one or more other prototype objects, but again the preference of the language designers was to just make it a callable function on the Number constructor itself; that's a recent ES6 addition to the spec of course.)
Finally note that in the particular case of the Number constructor, it's pretty rare that you'd actually explicitly instantiate a number object. Generally that happens implicitly when a number primitive value is used with the . or [ ] operators as if it were an object reference. Primitives are not objects, but the language automatically wraps a primitive value in a Number object in those cases, so the first example above would work the same if it were written like this:
var n2 = 2;
alert(n2.toExponential());
The variable n2 has a plain primitive 2 in it, but that will be wrapped in a Number instance in order to allow the method call.
I do not know whether you mean a program design perspective or a language (core library) design perspective, so I'll try to answer both.
Before we begin, please forget "class" or "instance" or "static".
JavaScript is not class based.
There only object and inheritance.
Now, let's see the object diagram.
Note that new Number does not inherits Number.
Neither prototype nor constructor is an inheriting relationship.
This means number instances inherits toExponential, toFixed, etc. but does not inherits parseFloat, parseInt etc.
So you call them like Number.parseFloat() and new Number(n).toFixed().
This is how JS is designed. If you don't like it you can design your own Number library.
For example, you may create your own Number that has toFixed methods on the Number object rather than on its prototype object, like this:
var SheepyNumber = {
toFixed: ( n ) => Number.toFixed( n )
}
SheepyNumber.toFixed( 3.14159265358979323846 ) // Evaluates to '3'
Do not add toFixed to Number object. It may work for now,
But if later specifications introduces this function with any different in parameter or logic,
then your program may break when you use the standard implementation,
or a third party library may break if you keep your own implementation.
Either way, you lost.
Which leave us the question, why does JS not put toFixed to Number, like we just did, but instead put toFixed to Number.prototype?
The obvious answer is this is more object-oriented.
Since new Number has an internal value property, toFixed can take that value, instead of taking in an extra argument.
The real answer is no one knows.
JavaScript copied Java for its core API - you can find most of these methods in the Java Float class.
Some of these Java methods are instance methods (corresponds to methods on Number.prorotype), some are static (corresponds to methods on Number), but most are both - including a counterpart of toFixed.
Why JavaScript did not put isFinite or isNaN to Number.prototype?
Why did no browsers implement toFixed on Number which can co-exists with the one on Number.prototype, during the first browser war that shaped the JavaScript as we know now?
Language design is an art.
And you may not always know who is responsible or why, because it has been shaped by many hands.

Function name convention for "convert foo to bar"

I have a very common pattern of "given a Foo, return a Bar," for example, given a user_id, return a User.
Is there a conventional naming pattern for these sorts of functions? Following Joel on Software, I've personally used a lot of bar_from_foo(), but I rarely see other people do this and it quickly becomes verbose, e.g.
widgets = user_widgets_from_user(user_from_param_map(params))
Is there a conventional way to name, or namespace (e.g. User.from_map()) in any of the popular languages out there? I am particularly interested in Python but any language you can think of would br useful.
I would take advantage of Clojure's naming flexibility and call it:
(defn foo->bar [] ...)
To me that makes the intent quite clear and it's pretty short.
In Python, and various other OO languages, this should be a constructor on Bar that takes a single Foo as its only argument. Since Python doesn't do method overloading (and attempts to emulate it are usually fragile), if Bar.__init__ already takes a different signature, then the convention is exactly your last one. Importantly, this is usually defined as a class method rather than a static method (for the benefit of subclasses):
class Bar:
#classmethod
def from_foo(cls, f):
'''Create a new Bar from the given Foo'''
ret = cls()
# ...
If you want to convert something into another, for example a string to an integer, the method is to be defined on the receiver, and hence its class is clear, so you should not put the receiver class as part of the method name: String#to_i, not String#string_to_i. This in one of the core ideas of object oriented programming (polymorphism).
If the receiver is too general to be assigned such method, for example if user_id is a mere string, and defining a method on String to convert it to a User does not look right, then you should define a constructor method on the class that you expect the return value to be: User.new or User.from_id.
I think it depends a lot on context and choosing a meaningful metaphor. ActiveRecord for instance uses the class method "find" for finding records in the database, a more meaningful idea than "input a user_id, output a user". For example:
User.find(user_id)
User.find_by_email(user_email)
For conversions, I usually like to write the conversion methods to make it easy to use in higher order functions. For example in ruby, conversions are often done with to_* instance methods, for example to convert a Foo to a Bar it would make sense to have a to_bar method for all foos, so you could write:
foo = Foo.new(...) # make a new Foo
bar = foo.to_bar # convert it to a Bar
And then to convert a bunch of foos, you could simply:
bars = foos.map(&:to_bar)
Ruby also tends to have Foo.parse(str) for converting a string to the object.
For javascript, I like having class methods (which I got from standard ml), for example:
Foo.toBar = function(foo) {
return new Bar(...);
};
And then you can map over it as well (using underscore in this example):
var bars = _.map(foos, Foo.toBar);
the Standard ML convention is structure (class) methods. Example fn types:
Foo.toBar : foo -> bar
Foo.fromBar : bar -> foo
And you'd use it like:
val bar = Foo.toBar foo;
val bars = map Foo.toBar foos;
Why placing the type of the parameter the name of the function? I think it would be clearer something like
a_bar = bar_from(a_foo)
then you can rely on dynamic dispatch or overload in many languages... for example in Python the implementation could try to call x.toBar() if present or it could check for a global registry like Bar_builders[type(x)](x); in Lisp you could rely on methods; in C++ on overloads...

How to list methods of inherited classes in CoffeeScript or Javascript

Example:
class Complex
constructor: (#a, #b) ->
conjugate: -> new Complex(#a, -#b)
class ComplexSon extends Complex
constructor: (#a, #b) ->
#c = 3.14
magnitude: -> #a*#a + #b*#b
I have defined the following method:
dumpMethods = (klass) ->
Object.getOwnPropertyNames(klass.property).sort()
Test cases:
dumpMethods(Complex) == ['conjugate', 'constructor']
# success
dumpMethods(ComplexSon) == ['conjugate', 'constructor', 'magnitude']
# fails, returns ['constructor', 'magnitude']
What is the correct definition of dumpMethods?
ban,
Javascript (and consequently coffee script) use prototypal objects.
I suggest you read about it because the matter is rather complex.
Trying to summarize, each object has a prototype. The prototype is itself an object, has its own properties, and also has a prototype, and so on.
The chain of prototypes actually defines the class hierarchy. So in you case, ComplexSon will have a prototype that is Complex, that will have a prototype that is Object itself, the root of all object hierarchies in javascript.
When you call a method on an instance, javascript will search for that method on that instance, then in its prototype, then up on the chain. The first one found is the method it will execute.
As in most programming languages, you can go "up" the hierarchy and see superclasses, but rarely you can go down cause it is rarely needed by the language interpreter itself. However there are some workarounds, like ones used by prototype, to know the subclasses of a given class, but AFAIK they are not in the lauage itself, most often they simply keeps track of defined classes.
Regarding the methods, in your code you are looking at the properties of ComplexSon, that correctly consist of only two methods. The other one (coniugate) is not there cause it is reached via the prototype, you can list them all by recursively going up the prototype chain.
Based on Gianni's answer I ended up with the following implementation.
dumpMethods traverses against the root class, Object, but avoids listing the methods in Object.
dumpMethods = (klass) ->
res = []
k = klass.prototype
while k
names = Object.getOwnPropertyNames(k)
res = res.concat(names)
k = Object.getPrototypeOf(k)
break if not Object.getPrototypeOf(k) # suppress Object
res.unique().sort()

Prototypal programming in Python

Javascript uses a prototype-based model for its objects. Nevertheless, the language is very flexible, and it is easy to write in a few lines functions which replace other kind on constructs. For instance, one can make a class function, emulating the standard class behaviour, including inheritance or private members. Or one can mimcìic functional tools by writing, for instance, a curry function which will take a function and some of its arguments and return the partially applied function.
I was wondering whether it is possible to do the reverse and imitate the prototypal method in more classical languages. In particular I have been thinking a bit whether it is possible to imitate prototypes in Python, but the lack of support for anonymous functions (more general than lambdas) leaves me stuck.
Is it possible to write some functions to mimic propotypes in class-based languages, in particular in Python?
EDIT Let me give some example of how one could go implementing such a thing (but I'm not really able to do it all).
First, the thing which most closely resembles Javascript objects is a Python dictionary. So we could have simple objects like
foo = {
'bar': 1,
'foobar': 2
}
Of course we want to add method, and this is not a problem as long as the method fits in a lambda
foo = {
'bar': 1,
'foobar': 2,
'method': lambda x: x**2
}
So now we can call for instance
foo['method'](2)
>>> 4
Now if we had arbitrary functions as methods we could go on like this. First we need the functions inside foo to have access to foo itself; otherwise they are just ordinary functions and not methods.
I guess one could do this by applying a makeObject function to foo, which loops through foo values and, whenever finds a value that is callable, modifies its __call__ attribute to pass foo as its first argument.
At this stage we would have self standing objects, which can be declared without the need of creating classes.
Then we need to be able to give foo a prototype, which can be passed as a second argument of the makeObject function. The function should modify foo.__getattr__ and foo.__setattr__ as follows: whenever the attribute is not found in foo, it should be searched in foo.prototype.
So, I think I would be able to implement this, expect for one thing: I cannot think any ways to declare methods more complicated than lambdas, except for declaring them beforehand and attaching them to my object. The problem is the lack of anonymous functions. I asked here because maybe some Python guru could find some clever way to circumvent this.
It's much easier in Python than in JS. Your JS code could be replaced with this in Python:
>>> class Foo(object):
... pass
>>> foo = Foo()
>>> foo.bar = 1
>>> foo.foobar = 2
Then you can add methods dynamically as well
>>> foo.method = lambda x: x**2
>>> foo.method(2)
4
For methods more complicated than lambdas, you declare them as functions, and they will have access to foo itself, no problems:
>>> def mymethod(self, bar, foobar):
... self.bar = bar
... self.foobar = foobar
>>> foo.mymethod = mymethod
>>> foo.mymethod(1,2)
>>> foo.bar
1
>>> foo.foobar
2
Or for that matter:
>>> mymethod(foo, 3, 4)
>>> foo.bar
3
>>> foo.foobar
4
Same thing.
So as you see, doing what your example is in Python is almost ridiculously simple. The question is why. :) I mean, this would be better:
>>> class Foo(object):
... def __init__(self, bar, foobar):
... self.bar = bar
... self.foobar = foobar
... def method(self, x):
... return x**2
Each time you read some property of Python object, method __getattribute__ is called, so you can overload it and completely control access to object's attributes. Nevertheless, for your task a bit different function - __getattr__ - may be used. In contrast to __getattribute__ it is called only if normal lookup for an attribute failed, i.e. at the same time, as prototype lookup in JavaScript starts. Here's usage:
...
def __getattr__(self, name):
if hasattr(prototype, name)
return getattr(prototype, name)
else:
raise AttributeError
Also pay attention to this question, since it has some notes on old and new style objects.
This implementation contains one important enhancement over otherwise similar implementations in other answers and on the internet: the correct inheritance of methods from the prototype. If a value obtained from the prototype is a a bound instance method -- and to cover weird corner cases the method is also actually bound to that prototype -- then the method's underlying function is extracted and a new method binding that function to the calling object is returned
import types
import inspect
class Proto(object):
def __new__(self, proto, *args, **kw):
return super(Proto, self).__new__(self, *args, **kw)
def __init__(self, proto, *args, **kw):
self.proto = proto
super(Proto, self).__init__(*args, **kw)
def __getattr__(self, name):
try:
attr = getattr(self.proto, name)
# key trick: rebind methods from the prototype to the current object
if (inspect.ismethod(attr) and attr.__self__ is self.proto):
attr = types.MethodType(attr.__func__, self)
return attr
except AttributeError:
return super(Proto, self).__getattr__(name)
This should fully implement prototypal inheritance as I understand it.
One restriction is that classes inheriting from Proto must have Proto first in their MRO because __new__ and __init__ have the prototype as the first parameter, which they drop when they delegate to super.
Here is a use example:
from prototypal import Proto
class A(Proto):
x = "This is X"
def getY(self):
return self._y
class B(Proto):
_y = "This is Y"
class C(object):
def __getattr__(self, name):
return "So you want "+name
class D(B,C):
pass
a = A(None) # a has no proto
b = B(a) # a is the proto for b
print b.x
print b.getY() # this will not work in most implementations
d = D(a) # a is the proto for d
print d.x
print d.getY()
print d.z
Here is the gist
Short version, yes but it's a bit more complicated than JS.
From Metaclass programming in Python :
>>> class ChattyType(type):
... def __new__(cls, name, bases, dct):
... print "Allocating memory for class", name
... return type.__new__(cls, name, bases, dct)
... def __init__(cls, name, bases, dct):
... print "Init'ing (configuring) class", name
... super(ChattyType, cls).__init__(name, bases, dct)
...
>>> X = ChattyType('X',(),{'foo':lambda self:'foo'})
Allocating memory for class X
Init'ing (configuring) class X
>>> X, X().foo()
(<class '__main__.X'>, 'foo')
Also check What is a metaclass in Python.
Edit : Check Prototype based OO, which is the closest thing you will get, but it will always come down to either using a lambda or just defining the function outside and adding a pointer to it to the class object.
I know this is quite old, but I though I'd add my $.02:
https://gist.github.com/4142456
The only problematic thing here is adding methods. JavaScript has a far more elegant syntax with its function literals, and it's truly hard to beat that. Lambda's don't quite cut it. So my solution was to add an awkward method method for adding methods.
Doctests are included in the gist, and it all works.
EDIT:
Updated gist to no longer use method instance method. However, we still need to define the function beforehand.
At any rate, the most important part of prototypal object model is implemented in that gist. Other things are simply syntactic sugar (would be nice to have them, but it doesn't mean prototypal object model cannot be used).

Categories