class or instance method

Scott David Daniels Scott.Daniels at Acm.Org
Sun Jun 21 23:23:41 CEST 2009


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))


--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list