0

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

Jaxx
  • 1,355
  • 2
  • 11
  • 19
  • 3
    To know what it does *internally*, you'd need to deep-dive into some C: https://github.com/python/cpython/blob/bb3e0c240bc60fe08d332ff5955d54197f79751c/Objects/funcobject.c#L782 Is that really what you want to know? – deceze May 25 '21 at 09:04
  • 1
    Here you can see a Python implementation: https://gist.github.com/carljm/3004616 – user2390182 May 25 '21 at 09:05

1 Answers1

2

@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
roscoe
  • 251
  • 1
  • 5
  • 1
    Since Python 2 is now EOL, it would be better to link to Python 3 docs instead: https://docs.python.org/3/howto/descriptor.html#class-methods – Gino Mempin May 25 '21 at 10:15