Difference between staticmethod and classmethod

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

    I think a better question is "When would you use @classmethod vs @staticmethod?"

    @classmethod allows you easy access to private members that are associated to the class definition. this is a great way to do singletons, or factory classes that control the number of instances of the created objects exist.

    @staticmethod provides marginal performance gains, but I have yet to see a productive use of a static method within a class that couldn't be achieved as a standalone function outside the class.

提交回复
热议问题