Django的classonlymethod有什么用?
下面是源代码:
class classonlymethod(classmethod):
def __get__(self, instance, owner):
if instance is not None:
raise AttributeError("This method is available only on the view class.")
return super(classonlymethod, self).__get__(instance, owner)
虽然我知道classonlymethod只能在类上调用,而不能在实例上调用,这和Python的classmethod不一样,但为什么我们需要这样的“限制”呢?
在网上关于classonlymethod的信息不多,任何简单易懂的例子都会很受欢迎。
1 个回答
5
这个功能在基于类的视图中使用,主要是在as_view
方法上,目的是给那些试图在实例上调用它的人提供一个清晰的错误信息。
我不太确定是谁最早决定这个是必须的。