tags:

views:

81

answers:

1

In Python, I'd like to be able to create a function that behaves both as a class function and an instance method, but with the ability to change behaviors. The use case for this is for a set of serializable objects and types. As an example:

>>> class Thing(object):
    #...
>>> Thing.to_json()
'A'
>>> Thing().to_json()
'B'

I know that given the definition of classmethod() in funcobject.c in the Python source, this looks like it'd be simple with a C module. Is there a way to do this from within python?

Thanks!

With the hint of descriptors, I was able to do it with the following code:

class combomethod(object):
    def __init__(self, method):
        self.method = method

    def __get__(self, obj=None, objtype=None):
        @functools.wraps(self.method)
        def _wrapper(*args, **kwargs):
            if obj is not None:
                return self.method(obj, *args, **kwargs)
            else:
                return self.method(objtype, *args, **kwargs)
        return _wrapper

Thank you Alex!

+2  A: 

Sure, you just need to define your own descriptor type. There's an excellent tutorial on Python descriptors here.

Alex Martelli