class or instance method

Hrvoje Niksic hniksic at xemacs.org
Wed Jun 17 08:40:45 EDT 2009


Paul Johnston <paul.paj at gmail.com> writes:

> I would like to have a method that is both a classmethod and an
> instancemethod. So:
>
> class MyClass(object):
>   @class_or_instance
>   def myfunc(cls_or_self):
>     pass
>
> The semantics I'd like are:
> When you call MyClass.myfunc, it gets passed a class
> When you call MyClass().myfunc, it gets passed an instance

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)

>>> class MyClass(object):
...   @class_or_instance
...   def myfunc(cls_or_self):
...     return cls_or_self
...
>>> MyClass.myfunc()
<class '__main__.MyClass'>
>>> MyClass().myfunc()
<__main__.MyClass object at 0xb7a248cc>

You might want to use functools.wrap to return named functions rather
than unnamed lambdas, but you get the idea.



More information about the Python-list mailing list