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!
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.
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.
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.
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.
Sure, you just need to define your own descriptor type. There's an excellent tutorial on Python descriptors here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With