Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between django classonlymethod and python classmethod?

Tags:

python

django

Why is there a need for Django to introduce the decorator classonlymethod ? Why can't it reuse python classmethod?

like image 396
canadadry Avatar asked Nov 15 '11 08:11

canadadry


People also ask

When should I use Classmethod in Python?

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.

What is @classonlymethod?

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.

What is a Classmethod?

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.

What is the difference between a function decorated with @staticmethod and one decorated with Classmethod?

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


1 Answers

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.

like image 146
madjar Avatar answered Oct 24 '22 06:10

madjar