Difference between staticmethod and classmethod

后端 未结 28 2914
一整个雨季
一整个雨季 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:44

    @staticmethod just disables the default function as method descriptor. classmethod wraps your function in a container callable that passes a reference to the owning class as first argument:

    >>> class C(object):
    ...  pass
    ... 
    >>> def f():
    ...  pass
    ... 
    >>> staticmethod(f).__get__(None, C)
    
    >>> classmethod(f).__get__(None, C)
    >
    

    As a matter of fact, classmethod has a runtime overhead but makes it possible to access the owning class. Alternatively I recommend using a metaclass and putting the class methods on that metaclass:

    >>> class CMeta(type):
    ...  def foo(cls):
    ...   print cls
    ... 
    >>> class C(object):
    ...  __metaclass__ = CMeta
    ... 
    >>> C.foo()
    
    

提交回复
热议问题