class or instance method
Miles Kaufmann
milesck at umich.edu
Sun Jun 21 17:56:01 EDT 2009
On Jun 21, 2009, at 5:23 PM, Scott David Daniels wrote:
> Hrvoje Niksic wrote:
>> ...
>> class class_or_instance(object):
>> def __init__(self, fn):
>> self.fn = fn
>> def __get__(self, obj, cls):
>> if obj is not None:
>> return lambda *args, **kwds: self.fn(obj, *args, **kwds)
>> else:
>> return lambda *args, **kwds: self.fn(cls, *args, **kwds)
>> ...
>
> Just to polish a bit:
>
> import functools
>
> class ClassOrInstance(object):
> def __init__(self, fn):
> self._function = fn
> self._wrapper = functools.wraps(fn)
>
> def __get__(self, obj, cls):
> return self._wrapper(functools.partial(self._function,
> cls if obj is None else obj))
from types import MethodType
class ClassOrInstance(object):
def __init__(self, func):
self._func = func
def __get__(self, obj, cls):
return MethodType(self._func, cls if obj is None else obj, cls)
-Miles
More information about the Python-list
mailing list