I\'m trying to write a decorator that provides method overloading functionality to python, similar to the one mentioned in PEP 3124.
The decorator I wrote works grea
Essentially, your Overload
class needs a __get__
method:
def __get__(self, obj, cls):
# Called on access of MyClass.print_first_item.
# We return a wrapper which calls our
print "get", self, obj, cls
if obj is None:
# a function would do some checks here, but we leave that.
return self
else:
return lambda *a, **k: self(obj, *a, **k)
Why?
Well, you use your Overload
object as a kind of function replacement. You want it, like a function, to represent itself in a method context with different signature.
Short explanation how method access works:
object.meth(1, 2)
gets translated to
object.__dict__['meth'].__get__(object, type(object))(1, 2)
A function's __get__()
returns a method object which wraps the function by prepending the object to the parameter list (where it results in self
):
realmethod = object.__dict__['meth'].__get__(object, type(object))
realmethod(1, 2)
where realmethod
is a method object which knows the function to be called and the self
to be given to it and calls the "real" function appropriately by transforming the call into
meth(object, 1, 2)
.
This behaviour we imitate in this new __get__
method.