Difference between staticmethod and classmethod

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

    Static Methods:

    • Simple functions with no self argument.
    • Work on class attributes; not on instance attributes.
    • Can be called through both class and instance.
    • The built-in function staticmethod()is used to create them.

    Benefits of Static Methods:

    • It localizes the function name in the classscope
    • It moves the function code closer to where it is used
    • More convenient to import versus module-level functions since each method does not have to be specially imported

      @staticmethod
      def some_static_method(*args, **kwds):
          pass
      

    Class Methods:

    • Functions that have first argument as classname.
    • Can be called through both class and instance.
    • These are created with classmethod in-built function.

       @classmethod
       def some_class_method(cls, *args, **kwds):
           pass
      

提交回复
热议问题