共享方法#
- class astropy.utils.decorators.sharedmethod(function, /)[源代码]#
基类:
classmethod
这是一个方法修饰符,它同时允许实例方法和
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
实现可以单独编写。如果班上的学生 metaclass 具有一个与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