Search code examples
pythonpython-decoratorsclass-method

What does @classmethod decorator in Python do internally?


I know how to use @classmethod decorator, but I wonder what does it do internally to the function, which it decorates? How does it take the class/object, on which it is called to pass it as first parameter of the decorated function?

Thanks


Solution

  • @classmethod is a Python descriptor - Python 3, Python 2

    You can call decorated method from an object or class.

    class Clazz:
    
        @classmethod
        def f(arg1):
            pass
    
    o = Clazz()
    

    If you call:

    o.f(1)
    

    It will be acctually f(type(o), *args) called.

    If you call:

    Clazz.f(1)
    

    It will be acctually f(Clazz, *args) called.

    As in doc, pure-python classmethod would look like:

    class ClassMethod(object):
    "Emulate PyClassMethod_Type() in Objects/funcobject.c"
    
    def __init__(self, f):
        self.f = f
    
    def __get__(self, obj, klass=None):
        if klass is None:
            klass = type(obj)
        def newfunc(*args):
            return self.f(klass, *args)
        return newfunc