Why use classmethod instead of staticmethod?

This question already has an answer here:

  • What is the difference between @staticmethod and @classmethod in Python? 24 answers

  • There's little difference in your example, but suppose you created a subclass of Foo and called the create_new method on the subclass...

    class Bar(Foo):
        pass
    
    obj = Bar.create_new()
    

    ...then this base class would cause a new Bar object to be created...

    class Foo:
        @classmethod
        def create_new(cls):
            return cls()
    

    ...whereas this base class would cause a new Foo object to be created...

    class Foo:
        @staticmethod
        def create_new():
            return Foo()
    

    ...so the choice would depend which behavior you want.


    Yes, those two classes would do the same.

    However, now imagine a subtype of that class:

    class Bar (Foo):
        pass
    

    Now calling Bar.create_new does something different. For the static method, you get a Foo . For the class method, you get a Bar .

    So the important difference is that a class method gets the type passed as a parameter.


    From the docs, a class method receives its class as an implicit argument, while static methods are unaware of the class in which they reside.

    This can be useful in situations where you have an inherited static method that you want to override with different behaviour in the subclass.

    链接地址: http://www.djcxy.com/p/9168.html

    上一篇: Python静态方法,为什么?

    下一篇: 为什么使用classmethod而不是staticmethod?