25

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
  • 1
    Why would you need to serialize the type? Commented Apr 7, 2010 at 2:48
  • 1
    there are plenty of reasons. In my particular problem, serializing the type allows us to create the specifications in an RPC system. Commented Apr 7, 2010 at 3:02

1 Answer 1

9

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

Sign up to request clarification or add additional context in comments.

2 Comments

For an update 9 years later, the Python documentation now hosts this tutorial from Raymond Hettinger, and it's no longer at the link posted. (One can check archive.org for a cached version of the original, but it's just a slightly smaller version of the one on the Python docs).
This answer would be magnitudes more useful if it provided an outline solution to question not just a research pointer. It would win my upvote only then.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.