3

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

2

1 Answer 1

4

@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
Sign up to request clarification or add additional context in comments.

2 Comments

Since Python 2 is now EOL, it would be better to link to Python 3 docs instead: docs.python.org/3/howto/descriptor.html#class-methods
"@classmethod is a Python descriptor" is not correct, actually @classmethod is a Python decorator, see the documentation reference: docs.python.org/3/library/functions.html#classmethod

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.