Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does @classmethod decorator in Python do internally? [duplicate]

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

like image 688
Jaxx Avatar asked Jan 22 '26 19:01

Jaxx


1 Answers

@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
like image 70
roscoe Avatar answered Jan 25 '26 09:01

roscoe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!