共享方法

class astropy.utils.decorators.sharedmethod[源代码]

基类:classmethod

这是一个方法修饰符,它允许instancemethod和 classmethod 同名。

使用时 sharedmethod 在类的主体中定义的方法上,可以对实例或类调用该方法。对于前者,实例的行为与第一个实例的引用类似 self 方法参数)::

>>> 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)

在后一种情况下,当 sharedmethod 直接从类调用,其行为类似于 classmethod ::

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

这也支持更高级的用法,其中 classmethod 实现可以单独编写。如果班级 元类 方法的名称与 sharedmethod ,元类上的版本被委派给:

>>> 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