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

前端 未结 2 841
粉色の甜心
粉色の甜心 2020-12-29 04:32

At what point do methods in Python acquire a get property? —As soon as they\'re defined in the class? Why does Python let me define a method without any argum

2条回答
  •  情歌与酒
    2020-12-29 04:55

    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
    

提交回复
热议问题