How does Ruby compare to Python?? How good is DESIGN of Rubycompared to Python?
Joe Mason
joe at notcharles.ca
Wed Feb 25 15:42:38 EST 2004
In article <mailman.100.1077717447.8594.python-list at python.org>, Dave Brueck wrote:
> def someFunc(callback):
> print callback(5,6)
>
> def functionCallback(a, b):
> return a + b
>
> class Foo:
> def methodCallback(self, a, b):
> return a * b
>
> then both these work:
>
> someFunc(functionCallback)
> f = Foo()
> someFunc(f.methodCallback)
>
> This is pretty darn useful and IMO quite Pythonic: the creator of the function
> and the creator of the callback have to agree on only the most minimal set of
> details - just those relating to the calling interface - leaving completely
> open any implementation details.
I still don't see how this is notable. Seems perfectly straightforward to
me - I'd just assume that's how it worked except in C++, about which I
never assume anything.
A better example of buond vs. unbound methods is this:
def boundFunc(callback):
print callback(5, 6)
def unboundFunc(obj, callback):
print callback(obj, 5, 6)
def functionCallback(a, b):
return a + b
class Foo:
def methodCallback(self, a, b):
return a * b + self.c
def setc(self, c):
self.c = c
>>> boundFunc(functionCallback)
11
>>> f = Foo()
>>> f.setc(3)
>>> boundFunc(f.methodCallback)
33
>>> unboundFunc(f, Foo.methodCallback)
33
For anyone who does care, the Ruby version is
def boundFunc(callback)
puts callback.call(5, 6)
end
def unboundFunc(obj, callback)
callback.bind(obj).call(5, 6)
end
def functionCallback(a, b)
return a + b
end
class Foo
def methodCallback(a, b)
return a * b + @c
end
def setc(c)
@c = c
end
end
> boundFunc(method(:functionCallback))
11
=> nil
> f = Foo.new
=> #<Foo:0x403119dc>
> f.setc(3)
=> 3
> boundFunc(f.method(:methodCallback))
33
=> nil
> unboundFunc(f, Foo.instance_method(:methodCallback))
=> 33
It's a little more cumbersome to manipulate functions because of the
extra calls to "call" and "bind", because "f.methodCallback" actually
calls the method with no params instead of returning a reference to it.
This is one of the things I dislike about Ruby, but it's not like
unbound methods are missing from the language.
(I was wrong when I said "unbound method" was a concept that had no
meaning to Ruby - it even had a "bind" method to support them. Didn't
know about that until I looked it up just now.)
Joe
More information about the Python-list
mailing list