In django.utils.tree.py:
def _new_instance(cls, children=None, connector=None, negated=False):
obj = Node(children, connector, negated)
obj.__class__ = cls
return obj
_new_instance = classmethod(_new_instance)
I don’t know what classmethod does in this code sample. Can someone explain what it does and how to use it?
classmethodis a decorator, wrapping a function, and you can call the resulting object on a class or (equivalently) an instance thereof:As you see, whether you define it directly or with decorator syntax, and whether you call it on the class or the instance, the
classmethodalways receives the class as its first argument.One of the main uses of classmethod is to define alternative constructors:
Now if you subclass
y, the classmethod keeps working, e.g.: