Mike Axiak
Mike Axiak

Reputation: 12004

Creating a method that is simultaneously an instance and class method

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!

Upvotes: 25

Views: 2404

Answers (1)

Alex Martelli
Alex Martelli

Reputation: 882791

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

Upvotes: 9

Related Questions