Why is there a need for Django to introduce the decorator classonlymethod
?
Why can't it reuse python classmethod
?
Example 3: Factory method using Class method Uses of classmethod() function are used in factory design patterns where we want to call many functions with the class name rather than an object.
The @classonlymethod decorator is used with . as_view() to make sure it isn't called on an instance of the class but instead is only called directly on the class. This is a good time to point out that we aren't going to directly create an instance of a class when using a CBV.
A class method is a method that is bound to a class rather than its object. It doesn't require creation of a class instance, much like staticmethod. The difference between a static method and a class method is: Static method knows nothing about the class and just deals with the parameters.
By using a staticmethod you aren't bound at all; there is no implicit first parameter. By using classmethod, you get as implicit first parameter the class you called the method on (if you called it directly on a class), or the class of the instance you called the method on (if you called it on an instance).
The best explanation is the source code itself:
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)
The difference is that a classmethod
can be called on an instance, having the same effect as calling it on the class, but the classonlymethod
can only be called on the class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With