django的classonlymethod和python的classmethod有什么区别?
为什么Django需要引入这个叫做classonlymethod
的装饰器呢?为什么不直接使用Python自带的classmethod
呢?
1 个回答
56
最好的解释就是源代码本身:
class classonlymethod(classmethod):
def __get__(self, instance, cls=None):
if instance is not None:
raise AttributeError("This method is available only on the class, not on instances.")
return super().__get__(instance, cls)
它们的区别在于,classmethod
可以在实例上调用,这样的效果和在类上调用是一样的;而classonlymethod
只能在类上调用。