Why use classmethod instead of staticmethod? [duplicate]

对着背影说爱祢 提交于 2019-12-03 01:16:26

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!