sharedmethod

class astropy.utils.decorators.sharedmethod[source]

Bases: classmethod

This is a method decorator that allows both an instancemethod and a classmethod to share the same name.

When using sharedmethod on a method defined in a class’s body, it may be called on an instance, or on a class. In the former case it behaves like a normal instance method (a reference to the instance is automatically passed as the first self argument of the method):

>>> class Example:
...     @sharedmethod
...     def identify(self, *args):
...         print('self was', self)
...         print('additional args were', args)
...
>>> ex = Example()
>>> ex.identify(1, 2)
self was <astropy.utils.decorators.Example object at 0x...>
additional args were (1, 2)

In the latter case, when the sharedmethod is called directly from a class, it behaves like a classmethod:

>>> Example.identify(3, 4)
self was <class 'astropy.utils.decorators.Example'>
additional args were (3, 4)

This also supports a more advanced usage, where the classmethod implementation can be written separately. If the class’s metaclass has a method of the same name as the sharedmethod, the version on the metaclass is delegated to:

>>> class ExampleMeta(type):
...     def identify(self):
...         print('this implements the {0}.identify '
...               'classmethod'.format(self.__name__))
...
>>> class Example(metaclass=ExampleMeta):
...     @sharedmethod
...     def identify(self):
...         print('this implements the instancemethod')
...
>>> Example().identify()
this implements the instancemethod
>>> Example.identify()
this implements the Example.identify classmethod