What's better about Ruby than Python?
Andrew Dalke
adalke at mindspring.com
Thu Aug 21 05:52:04 EDT 2003
Alex Martell:
> ... def __get__(self, obj, cls):
> ... self.obj = obj
> ... return self.cached_call
That's the part where I still lack understanding.
class Spam:
def f(self):
pass
f = CachedCall(f)
obj = Spam()
obj.f()
Under old-style Python
obj.f is the same as getattr(obj, "f")
which fails to find 'f' in the instance __dict__
so looks for 'f' in the class, and finds it
This is not a Python function, so it does not
get bound to self. It's simply returned.
obj.f() takes that object and calls it. In my original
code (not shown) I tried implementing a __call__
which did get called, but without the instance self.
Under new-style Python
obj.f is the same as getattr(obj, "f")
which fails to find 'f' in the instance __dict__ so
looks for 'f' in the class, and finds the CachedCall.
Python checks if the object implements __get__,
in which case it's called a descriptor. If so, it's
called with the 'obj' as the first parameter. The
return value of this call is used as the value for
the attribute.
Is that right?
> should closely mimic your semantics, including ignoring
> what I call obj and you call self in determining whether
> a certain set of argumens is cached.
Why should obj make a difference? There's only
one CachedCall per method per .... Ahh, because it's
in the class def, not the instance. Adding support for
that using a weak dict is easy.
Yeah, and my approach won't work with kwargs nor any
other unhashable element. Since I didn't know what the
Lisp code did nor how Lisp handles unhashable elements,
I decided just to implement the essential idea.
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list