Difference between staticmethod and classmethod

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

    @decorators were added in python 2.4 If you're using python < 2.4 you can use the classmethod() and staticmethod() function.

    For example, if you want to create a factory method (A function returning an instance of a different implementation of a class depending on what argument it gets) you can do something like:

    class Cluster(object):
    
        def _is_cluster_for(cls, name):
            """
            see if this class is the cluster with this name
            this is a classmethod
            """ 
            return cls.__name__ == name
        _is_cluster_for = classmethod(_is_cluster_for)
    
        #static method
        def getCluster(name):
            """
            static factory method, should be in Cluster class
            returns a cluster object for the given name
            """
            for cls in Cluster.__subclasses__():
                if cls._is_cluster_for(name):
                    return cls()
        getCluster = staticmethod(getCluster)
    

    Also observe that this is a good example for using a classmethod and a static method, The static method clearly belongs to the class, since it uses the class Cluster internally. The classmethod only needs information about the class, and no instance of the object.

    Another benefit of making the _is_cluster_for method a classmethod is so a subclass can decide to change it's implementation, maybe because it is pretty generic and can handle more than one type of cluster, so just checking the name of the class would not be enough.

提交回复
热议问题