How are methods, `classmethod`, and `staticmethod` implemented in Python? How are methods, `classmethod`, and `staticmethod` implemented in Python? python python

How are methods, `classmethod`, and `staticmethod` implemented in Python?


Check this out.

http://docs.python.org/howto/descriptor.html#static-methods-and-class-methods

You can also take a look at the source code for class and static method objects, in funcobject.c:

http://hg.python.org/cpython/file/69b416cd1727/Objects/funcobject.c

Class method object definition starts on line 694, while static method object definition starts on line 852. (I do find it kind of funny that they have items titled "method" in funcobject.c when methodobject.c also exists.)


For reference, from the first link in @JAB's answer

Using the non-data descriptor protocol, a pure Python version of staticmethod() would look like this:

class StaticMethod(object):    "Emulate PyStaticMethod_Type() in Objects/funcobject.c"    def __init__(self, f):        self.f = f    def __get__(self, obj, objtype=None):        return self.f

...

Using the non-data descriptor protocol, a pure Python version of classmethod() would look like this:

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