Difference between staticmethod and classmethod

后端 未结 28 2144
一整个雨季
一整个雨季 2020-11-21 06:11

What is the difference between a function decorated with @staticmethod and one decorated with @classmethod?

28条回答
  •  逝去的感伤
    2020-11-21 06:53

    I think giving a purely Python version of staticmethod and classmethod would help to understand the difference between them at language level.

    Both of them are non-data descriptors (It would be easier to understand them if you are familiar with descriptors first).

    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
    
    
    class ClassMethod(object):
        "Emulate PyClassMethod_Type() in Objects/funcobject.c"
        def __init__(self, f):
            self.f = f
    
        def __get__(self, obj, cls=None):
            def inner(*args, **kwargs):
                if cls is None:
                    cls = type(obj)
                return self.f(cls, *args, **kwargs)
            return inner
    

提交回复
热议问题