Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a method that is simultaneously an instance and class method

Tags:

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!

like image 387
Mike Axiak Avatar asked Apr 07 '10 02:04

Mike Axiak


People also ask

Is a method an instance of a class?

An instance method is a method that belongs to instances of a class, not to the class itself. To define an instance method, just omit static from the method heading. Within the method definition, you refer to variables and methods in the class by their names, without a dot.

What is the correct method for creating an instance method?

Calling An Instance Method operator to execute the block of code or action defined in the instance method. First, create instance variables name and age in the Student class. Next, create an instance method display() to print student name and age. Next, create object of a Student class to call the instance method.

Which of the following method can be called without creating an instance of a class?

Static Method Static methods are the methods in Java that can be called without creating an object of class. They are referenced by the class name itself or reference to the Object of that class.

Can an instance method call another instance method?

Instance methods can access instance variables and instance methods directly. This means a method that doesn't have a static modifier i.e. an instance method can access any non-static variable as well as call any non-static method.


1 Answers

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

like image 190
Alex Martelli Avatar answered Sep 21 '22 13:09

Alex Martelli