By Daryl Spitzer


2008-09-25 21:01:57 8 Comments

What is the difference between a function decorated with @staticmethod and one decorated with @classmethod?

23 comments

@blue_note 2019-05-21 10:47:50

The first argument differs:

  • normal method: first argument is (automatically) the current object
  • classmethod: first argument is (automatically) the class of the current object
  • staticmethod: first argument is not passed automatically

In more detail...

normal method

When an object's method is called, it is automatically given an extra argument self as its first argument. That is, method

def f(self, x, y)

must be called with 2 arguments. self is automatically passed, and it is the object itself.

class method

When the method is decorated

@classmethod
def f(cls, x, y)

the automatically provided argument is not self, but the class of self.

static method

When the method is decorated

@staticmethod
def f(x, y)

the method is not given any automatic argument at all. It is only given the parameters that it is called with.

usages

  • classmethod is mostly used for alternative constructors.
  • staticmethod does not use the state of the object. It could be a function external to a class. It only put inside the class for grouping functions with similar functionality (for example, like Java's Math class static methods)
class Point
    def __init__(self, x, y):
        self.x = x
        self.y = y

    @classmethod
    def frompolar(cls, radius, angle):
        """The `cls` argument is the `Point` class itself"""
        return cls(radius * cos(angle), radius * sin(angle))

    @staticmethod
    def angle(x, y):
        """this could be outside the class, but we put it here 
just because we think it is logically related to the class."""
        return atan(y, x)


p1 = Point(3, 2)
p2 = Point.frompolar(3, pi/4)

angle = Point.angle(3, 2)

@Gaurang Shah 2017-10-10 10:10:50

I started learning programming language with C++ and then Java and then Python and so this question bothered me a lot as well, until I understood the simple usage of each.

Class Method: Python unlike Java and C++ doesn't have constructor overloading. And so to achieve this you could use classmethod. Following example will explain this

Let's consider we have a Person class which takes two arguments first_name and last_name and creates the instance of Person.

class Person(object):

    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name

Now, if the requirement comes where you need to create a class using a single name only, just a first_name, you can't do something like this in Python.

This will give you an error when you will try to create an object (instance).

class Person(object):

    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name

    def __init__(self, first_name):
        self.first_name = first_name

However, you could achieve the same thing using @classmethod as mentioned below

class Person(object):

    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name

    @classmethod
    def get_person(cls, first_name):
        return cls(first_name, "")

Static Method: This is rather simple, it's not bound to instance or class and you can simply call that using class name.

So let's say in above example you need a validation that first_name should not exceed 20 characters, you can simply do this.

@staticmethod  
def validate_name(name):
    return len(name) <= 20

and you could simply call using class name

Person.validate_name("Gaurang Shah")

@unutbu 2009-11-03 19:13:48

Maybe a bit of example code will help: Notice the difference in the call signatures of foo, class_foo and static_foo:

class A(object):
    def foo(self, x):
        print "executing foo(%s, %s)" % (self, x)

    @classmethod
    def class_foo(cls, x):
        print "executing class_foo(%s, %s)" % (cls, x)

    @staticmethod
    def static_foo(x):
        print "executing static_foo(%s)" % x    

a = A()

Below is the usual way an object instance calls a method. The object instance, a, is implicitly passed as the first argument.

a.foo(1)
# executing foo(<__main__.A object at 0xb7dbef0c>,1)

With classmethods, the class of the object instance is implicitly passed as the first argument instead of self.

a.class_foo(1)
# executing class_foo(<class '__main__.A'>,1)

You can also call class_foo using the class. In fact, if you define something to be a classmethod, it is probably because you intend to call it from the class rather than from a class instance. A.foo(1) would have raised a TypeError, but A.class_foo(1) works just fine:

A.class_foo(1)
# executing class_foo(<class '__main__.A'>,1)

One use people have found for class methods is to create inheritable alternative constructors.


With staticmethods, neither self (the object instance) nor cls (the class) is implicitly passed as the first argument. They behave like plain functions except that you can call them from an instance or the class:

a.static_foo(1)
# executing static_foo(1)

A.static_foo('hi')
# executing static_foo(hi)

Staticmethods are used to group functions which have some logical connection with a class to the class.


foo is just a function, but when you call a.foo you don't just get the function, you get a "partially applied" version of the function with the object instance a bound as the first argument to the function. foo expects 2 arguments, while a.foo only expects 1 argument.

a is bound to foo. That is what is meant by the term "bound" below:

print(a.foo)
# <bound method A.foo of <__main__.A object at 0xb7d52f0c>>

With a.class_foo, a is not bound to class_foo, rather the class A is bound to class_foo.

print(a.class_foo)
# <bound method type.class_foo of <class '__main__.A'>>

Here, with a staticmethod, even though it is a method, a.static_foo just returns a good 'ole function with no arguments bound. static_foo expects 1 argument, and a.static_foo expects 1 argument too.

print(a.static_foo)
# <function static_foo at 0xb7d479cc>

And of course the same thing happens when you call static_foo with the class A instead.

print(A.static_foo)
# <function static_foo at 0xb7d479cc>

@Alcott 2011-09-19 03:08:01

I don't understand what's the catch for using staticmethod. we can just use a simple outside-of-class function.

@unutbu 2011-09-19 10:34:44

@Alcott: You might want to move a function into a class because it logically belongs with the class. In the Python source code (e.g. multiprocessing,turtle,dist-packages), it is used to "hide" single-underscore "private" functions from the module namespace. Its use, though, is highly concentrated in just a few modules -- perhaps an indication that it is mainly a stylistic thing. Though I could not find any example of this, @staticmethod might help organize your code by being overridable by subclasses. Without it you'd have variants of the function floating around in the module namespace.

@MestreLion 2012-05-03 09:50:15

... along with some explanation on where and why to use either instance, class or static methods. You didn't give a single word about it, but neither did the OP asked about it.

@MestreLion 2012-05-03 09:55:03

@Alcott: as unutbu said, static methods are an organization/stylistic feature. Sometimes a module have many classes, and some helper functions are logically tied to a a given class and not to the others, so it makes sense not to "pollute" the module with many "free functions", and it is better to use a static method than relying on the poor style of mixing classes and function defs together in code just to show they are "related"

@abarnert 2014-09-21 01:01:27

One more thing that might be worth adding is what A.foo means, since you've thoroughly explained the other 5 cases (a.foo, a.class_foo, a.static_foo, A.class_foo, and A.static_foo): an "unbound method" (2.x) or a plain-old function (3.x) that expects an A instance as its first argument.

@abarnert 2014-09-21 01:02:01

Also, I don't think you want to actually explain descriptors here, but a one-line blurb with a link to the descriptor HOWTO might be helpful.

@ArtOfWarfare 2015-01-29 18:12:48

I especially love the part after the last dividing line of this answer - I never realized before that a.foo would return what is essentially a curried function, and that's what it means when it says <bound method ...>

@tehwalrus 2015-03-28 20:00:54

One more use for @staticmethod - you can use it to remove cruft. I am implementing a programming language in Python - library-defined functions use a static execute method, where user-defined functions require instance arguments (i.e. the function body). This decorator eliminates "unused parameter self" warnings in PyCharm inspector.

@Dogweather 2015-08-03 21:29:59

"create inheritable alternative constructors." Can someone point to an example of that?

@t3chb0t 2018-02-12 19:04:04

One use people have found for class methods - how do you mean they have found? This sounds like it wasn't properly documented and people had to crack it first to understand its usefulness instead of reading about it.

@t3chb0t 2018-02-12 19:08:16

Wow, the documentation is really not helpful about it but it looks like it behavior is similar to a copy constructor... so much about python coolnes. When it comes to details it's not so cool anymore.

@patrick 2018-05-22 16:51:33

[object] a is bound to [method] foo : this wording is unintuitive to me. Wouldn't it be the other way round, the function is bound to the object?

@unutbu 2018-05-22 17:17:49

Keep in mind the context: In Python2 there are bound and unbound methods. Bound methods are the objects returned by inst.method where inst is an instance of a class and method is a method of the class. The bound method knows about inst. When calling the bound method, inst is automatically supplied as the first argument. Unbound methods (the thing returned by the expression cls.method) do not know about inst, and inst is not supplied as the first argument when the unbound method is called. From this point of view it is natural to say inst is bound to the method.

@Mikko Rantalainen 2019-04-26 07:18:55

TL;DR: @staticmethod is very similar to standalone function in the same namespace, except that @staticmethod is inherited by subclasses (and may be overridden by subclass). @classmethod is similar but gets the referenced class as it's first parameter. Unless you inherit from a class with @classmethod there's rarely a need for this because you already know the class you're writing.

@typhon04 2019-08-06 07:57:26

What happens if neither @staticmethod nor @classmethod is used?

@David Nathan 2019-01-24 12:56:46

You might want to consider the difference between:

Class A:
    def foo():  # no self parameter, no decorator
        pass

and

Class B:
    @staticmethod
    def foo():  # no self parameter
        pass

This has changed between python2 and python3:

python2:

>>> A.foo()
TypeError
>>> A().foo()
TypeError
>>> B.foo()
>>> B().foo()

python3:

>>> A.foo()
>>> A().foo()
TypeError
>>> B.foo()
>>> B().foo()

So using @staticmethod for methods only called directly from the class has become optional in python3. If you want to call them from both class and instance, you still need to use the @staticmethod decorator.

The other cases have been well covered by unutbus answer.

@Selva 2018-01-14 14:07:39

Let me tell the similarity between a method decorated with @classmethod vs @staticmethod first.

Similarity: Both of them can be called on the Class itself, rather than just the instance of the class. So, both of them in a sense are Class's methods.

Difference: A classmethod will receive the class itself as the first argument, while a staticmethod does not.

So a static method is, in a sense, not bound to the Class itself and is just hanging in there just because it may have a related functionality.

>>> class Klaus:
        @classmethod
        def classmthd(*args):
            return args

        @staticmethod
        def staticmthd(*args):
            return args

# 1. Call classmethod without any arg
>>> Klaus.classmthd()  
(__main__.Klaus,)  # the class gets passed as the first argument

# 2. Call classmethod with 1 arg
>>> Klaus.classmthd('chumma')
(__main__.Klaus, 'chumma')

# 3. Call staticmethod without any arg
>>> Klaus.staticmthd()  
()

# 4. Call staticmethod with 1 arg
>>> Klaus.staticmthd('chumma')
('chumma',)

@Michael Swartz 2018-06-25 02:38:52

My contribution demonstrates the difference amongst @classmethod, @staticmethod, and instance methods, including how an instance can indirectly call a @staticmethod. But instead of indirectly calling a @staticmethod from an instance, making it private may be more "pythonic." Getting something from a private method isn't demonstrated here but it's basically the same concept.

#!python3

from os import system
system('cls')
# %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %

class DemoClass(object):
    # instance methods need a class instance and
    # can access the instance through 'self'
    def instance_method_1(self):
        return 'called from inside the instance_method_1()'

    def instance_method_2(self):
        # an instance outside the class indirectly calls the static_method
        return self.static_method() + ' via instance_method_2()'

    # class methods don't need a class instance, they can't access the
    # instance (self) but they have access to the class itself via 'cls'
    @classmethod
    def class_method(cls):
        return 'called from inside the class_method()'

    # static methods don't have access to 'cls' or 'self', they work like
    # regular functions but belong to the class' namespace
    @staticmethod
    def static_method():
        return 'called from inside the static_method()'
# %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %

# works even if the class hasn't been instantiated
print(DemoClass.class_method() + '\n')
''' called from inside the class_method() '''

# works even if the class hasn't been instantiated
print(DemoClass.static_method() + '\n')
''' called from inside the static_method() '''
# %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %

# >>>>> all methods types can be called on a class instance <<<<<
# instantiate the class
democlassObj = DemoClass()

# call instance_method_1()
print(democlassObj.instance_method_1() + '\n')
''' called from inside the instance_method_1() '''

# # indirectly call static_method through instance_method_2(), there's really no use
# for this since a @staticmethod can be called whether the class has been
# instantiated or not
print(democlassObj.instance_method_2() + '\n')
''' called from inside the static_method() via instance_method_2() '''

# call class_method()
print(democlassObj.class_method() + '\n')
'''  called from inside the class_method() '''

# call static_method()
print(democlassObj.static_method())
''' called from inside the static_method() '''

"""
# whether the class is instantiated or not, this doesn't work
print(DemoClass.instance_method_1() + '\n')
'''
TypeError: TypeError: unbound method instancemethod() must be called with
DemoClass instance as first argument (got nothing instead)
'''
"""

@Thomas Wouters 2008-09-25 21:05:53

A staticmethod is a method that knows nothing about the class or instance it was called on. It just gets the arguments that were passed, no implicit first argument. It is basically useless in Python -- you can just use a module function instead of a staticmethod.

A classmethod, on the other hand, is a method that gets passed the class it was called on, or the class of the instance it was called on, as first argument. This is useful when you want the method to be a factory for the class: since it gets the actual class it was called on as first argument, you can always instantiate the right class, even when subclasses are involved. Observe for instance how dict.fromkeys(), a classmethod, returns an instance of the subclass when called on a subclass:

>>> class DictSubclass(dict):
...     def __repr__(self):
...         return "DictSubclass"
... 
>>> dict.fromkeys("abc")
{'a': None, 'c': None, 'b': None}
>>> DictSubclass.fromkeys("abc")
DictSubclass
>>> 

@Tony Meyer 2008-09-26 10:10:35

A staticmethod isn't useless - it's a way of putting a function into a class (because it logically belongs there), while indicating that it does not require access to the class.

@Thomas Wouters 2008-09-26 13:40:00

Hence only 'basically' useless. Such organization, as well as dependency injection, are valid uses of staticmethods, but since modules, not classes like in Java, are the basic elements of code organization in Python, their use and usefulness is rare.

@Ben James 2010-03-12 09:11:19

What's logical about defining a method inside a class, when it has nothing to do with either the class or its instances?

@haridsv 2010-04-08 01:32:26

Perhaps for the inheritance sake? Static methods can be inherited and overridden just like instance methods and class methods and the lookup works as expected (unlike in Java). Static methods are not really resolved statically whether called on the class or instance, so the only difference between class and static methods is the implicit first argument.

@Imbrondir 2011-08-22 11:58:43

They also create a cleaner namespace, and makes it easier to understand the function have something to do with the class.

@Ethan Furman 2011-11-08 19:50:04

@BenJames: A staticmethod should have something to do with the class its defined in, it just doesn't need either class nor instance data to do its job. (see stackoverflow.com/questions/7855237)

@Adam Parkin 2012-03-02 23:17:22

So which is better: having a Math class with methods like sin, cos, etc, or having a Math module with functions sin, cos, etc. Seems to me that the latter would be preferable, so I'm hard pressed to think of a possible case where staticmethod would be useful. Helper methods I suppose are a potential case, but if a helper is so general as to not need anything from the class or a class instance, you really do have to wonder if it would be better served as a utility routine in a library.

@Jonathan 2012-04-13 16:04:38

When you have a class instance its often simpler to call inst.method() rather than module.method(). Sometimes you don't even know which module you're using, Python is a dynamic language after all...

@MestreLion 2012-05-03 09:40:59

-1: This answer A) gives a very corner-case feature of class method as an explanation of its utility (so they are only useful when subclassing to allow you the name of the subclass, really?), and B) implies "static methods should be module methods", which, although they semantically are, it makes a lot or sense to use them if your module defines many classes, and a given helper function only applies to a given class. So a very poor answer with lots of misconceptions imho.

@Thomas Wouters 2012-05-05 22:57:10

Classmethods aren't for 'allowing you the name of the subclass', they're so you can know what class the method was called on. They give you the class object, not the name. That is, in fact, their entire purpose.

@amit 2012-06-02 08:25:24

-1 from me too for the reasons in the comments. I find staticmethods at least as useful as classmethods in the presence of inheritance-based lookup, as described by @haridsv. See stackoverflow.com/questions/5060172/… . While implementing the template method design pattern, I will prefer staticmethod over classmethod, since the staticmethod has a lesser argument.

@Shengjie 2013-06-16 13:20:31

Indeed, static method is not useless, from method access perspective, it doesn't make difference if you just put it as part of the module. But imagine, you might have cases like, you have a module including several classes, the static method might just logically belong to one class other than the parent module. @haridsv static method can't be overridden, this applies to both Java and Python, they can be inherited but not overridden.

@haridsv 2013-06-27 16:02:05

@Shengjie see the example here: gist.github.com/haridsv/5877544. B.iden() is inherited by D, and when iden() calls identify() via self, Python resolves the method dynamically and finds the overridden method in D.

@lpapp 2013-11-07 08:54:07

@MestreLion: I agree with you here. I am not sure why this answer is so upvoted. It is really poor, and has some misconceptions.

@Pavel Šimerda 2016-09-22 12:46:34

Can't you just use a @classmethod instead of @staticmethod and ignore cls? You can only call it using the class object or an instance object anyway, right?

@Steve Harrison 2017-04-30 16:59:08

Adding to tonys comment: A staticmethod isn't useless - it's a way of putting * a loosly coupled function* into *its related * class (because it logically belongs there and one may not want to put the function in utility file)

@JL Peyret 2017-07-02 23:31:29

A lot of systems use classes as a configuration point. For example, Django's model classes allow configuration of fields, admin behavior, etc... However, if you want to "configure" functions - like say a formatting function they would (wo staticmethod) need to be class-based, whether that makes sense or not. A generic html formatting function does not necessarily need to know about a class IF the only thing it does is tweak html. Staticmethods allow you to choose not to bother with class or instance bindings.

@cowbert 2018-01-09 23:45:59

Another case for staticmethod is for a closure that is coupled to the class, because the staticmethod's inner function(s) do refer to the instance or class. This can happen if you are writing an inherited class- or instance- specific decorator. Decoupling the closure/outer function from the class makes no semantic sense in this case, because its inner function(s) do need access to either the class or instance.

@Du D. 2016-04-22 15:40:20

To decide whether to use @staticmethod or @classmethod you have to look inside your method. If your method accesses other variables/methods in your class then use @classmethod. On the other hand, if your method does not touches any other parts of the class then use @staticmethod.

class Apple:

    _counter = 0

    @staticmethod
    def about_apple():
        print('Apple is good for you.')

        # note you can still access other member of the class
        # but you have to use the class instance 
        # which is not very nice, because you have repeat yourself
        # 
        # For example:
        # @staticmethod
        #    print('Number of apples have been juiced: %s' % Apple._counter)
        #
        # @classmethod
        #    print('Number of apples have been juiced: %s' % cls._counter)
        #
        #    @classmethod is especially useful when you move your function to other class,
        #       you don't have to rename the class reference 

    @classmethod
    def make_apple_juice(cls, number_of_apples):
        print('Make juice:')
        for i in range(number_of_apples):
            cls._juice_this(i)

    @classmethod
    def _juice_this(cls, apple):
        print('Juicing %d...' % apple)
        cls._counter += 1

@Algebra 2017-12-12 09:40:50

Analyze @staticmethod literally providing different insights.

A normal method of a class is an implicit dynamic method which takes the instance as first argument.
In contrast, a staticmethod does not take the instance as first argument, so is called 'static'.

A staticmethod is indeed such a normal function the same as those outside a class definition.
It is luckily grouped into the class just in order to stand closer where it is applied, or you might scroll around to find it.

@Tushar Vazirani 2017-12-01 10:38:02

Class methods, as the name suggests, are used to make changes to classes and not the objects. To make changes to classes, they will modify the class attributes(not object attributes), since that is how you update classes. This is the reason that class methods take the class(conventionally denoted by 'cls') as the first argument.

class A(object):
    m=54

    @classmethod
    def class_method(cls):
        print "m is %d" % cls.m

Static methods on the other hand, are used to perform functionalities that are not bound to the class i.e. they will not read or write class variables. Hence, static methods do not take classes as arguments. They are used so that classes can perform functionalities that are not directly related to the purpose of the class.

class X(object):
    m=54 #will not be referenced

    @staticmethod
    def static_method():
        print "Referencing/calling a variable or function outside this class. E.g. Some global variable/function."

@vijay 2017-09-20 16:57:20

@classmethod : can be used to create a shared global access to all the instances created of that class..... like updating a record by multiple users.... I particulary found it use ful when creating singletons as well..:)

@static method: has nothing to do with the class or instance being associated with ...but for readability can use static method

@Laxmi 2016-10-03 10:41:18

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
    

@Aaron Hall 2015-01-23 20:01:20

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

You may have seen Python code like this pseudocode, which demonstrates the signatures of the various method types and provides a docstring to explain each:

class Foo(object):

    def a_normal_instance_method(self, arg_1, kwarg_2=None):
        '''
        Return a value that is a function of the instance with its
        attributes, and other arguments such as arg_1 and kwarg2
        '''

    @staticmethod
    def a_static_method(arg_0):
        '''
        Return a value that is a function of arg_0. It does not know the 
        instance or class it is called from.
        '''

    @classmethod
    def a_class_method(cls, arg1):
        '''
        Return a value that is a function of the class and other arguments.
        respects subclassing, it is called with the class it is called from.
        '''

The Normal Instance Method

First I'll explain a_normal_instance_method. This is precisely called an "instance method". When an instance method is used, it is used as a partial function (as opposed to a total function, defined for all values when viewed in source code) that is, when used, the first of the arguments is predefined as the instance of the object, with all of its given attributes. It has the instance of the object bound to it, and it must be called from an instance of the object. Typically, it will access various attributes of the instance.

For example, this is an instance of a string:

', '

if we use the instance method, join on this string, to join another iterable, it quite obviously is a function of the instance, in addition to being a function of the iterable list, ['a', 'b', 'c']:

>>> ', '.join(['a', 'b', 'c'])
'a, b, c'

Bound methods

Instance methods can be bound via a dotted lookup for use later.

For example, this binds the str.join method to the ':' instance:

>>> join_with_colons = ':'.join 

And later we can use this as a function that already has the first argument bound to it. In this way, it works like a partial function on the instance:

>>> join_with_colons('abcde')
'a:b:c:d:e'
>>> join_with_colons(['FF', 'FF', 'FF', 'FF', 'FF', 'FF'])
'FF:FF:FF:FF:FF:FF'

Static Method

The static method does not take the instance as an argument.

It is very similar to a module level function.

However, a module level function must live in the module and be specially imported to other places where it is used.

If it is attached to the object, however, it will follow the object conveniently through importing and inheritance as well.

An example of a static method is str.maketrans, moved from the string module in Python 3. It makes a translation table suitable for consumption by str.translate. It does seem rather silly when used from an instance of a string, as demonstrated below, but importing the function from the string module is rather clumsy, and it's nice to be able to call it from the class, as in str.maketrans

# demonstrate same function whether called from instance or not:
>>> ', '.maketrans('ABC', 'abc')
{65: 97, 66: 98, 67: 99}
>>> str.maketrans('ABC', 'abc')
{65: 97, 66: 98, 67: 99}

In python 2, you have to import this function from the increasingly less useful string module:

>>> import string
>>> 'ABCDEFG'.translate(string.maketrans('ABC', 'abc'))
'abcDEFG'

Class Method

A class method is a similar to an instance method in that it takes an implicit first argument, but instead of taking the instance, it takes the class. Frequently these are used as alternative constructors for better semantic usage and it will support inheritance.

The most canonical example of a builtin classmethod is dict.fromkeys. It is used as an alternative constructor of dict, (well suited for when you know what your keys are and want a default value for them.)

>>> dict.fromkeys(['a', 'b', 'c'])
{'c': None, 'b': None, 'a': None}

When we subclass dict, we can use the same constructor, which creates an instance of the subclass.

>>> class MyDict(dict): 'A dict subclass, use to demo classmethods'
>>> md = MyDict.fromkeys(['a', 'b', 'c'])
>>> md
{'a': None, 'c': None, 'b': None}
>>> type(md)
<class '__main__.MyDict'>

See the pandas source code for other similar examples of alternative constructors, and see also the official Python documentation on classmethod and staticmethod.

@zangw 2015-11-16 02:00:50

The definitive guide on how to use static, class or abstract methods in Python is one good link for this topic, and summary it as following.

@staticmethod function is nothing more than a function defined inside a class. It is callable without instantiating the class first. It’s definition is immutable via inheritance.

  • Python does not have to instantiate a bound-method for object.
  • It eases the readability of the code, and it does not depend on the state of object itself;

@classmethod function also callable without instantiating the class, but its definition follows Sub class, not Parent class, via inheritance, can be overridden by subclass. That’s because the first argument for @classmethod function must always be cls (class).

  • Factory methods, that are used to create an instance for a class using for example some sort of pre-processing.
  • Static methods calling static methods: if you split a static methods in several static methods, you shouldn't hard-code the class name but use class methods

@hard_working_ant 2018-05-02 03:38:58

Thanks @zangw - the inherited immutability of static function is the key difference it seems

@Jens Timmerman 2012-02-24 09:32:32

@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.

@Adam Parkin 2016-09-29 17:02:51

Another consideration with respect to staticmethod vs classmethod comes up with inheritance. Say you have the following class:

class Foo(object):
    @staticmethod
    def bar():
        return "In Foo"

And you then want to override bar() in a child class:

class Foo2(Foo):
    @staticmethod
    def bar():
        return "In Foo2"

This works, but note that now the bar() implementation in the child class (Foo2) can no longer take advantage of anything specific to that class. For example, say Foo2 had a method called magic() that you want to use in the Foo2 implementation of bar():

class Foo2(Foo):
    @staticmethod
    def bar():
        return "In Foo2"
    @staticmethod
    def magic():
        return "Something useful you'd like to use in bar, but now can't" 

The workaround here would be to call Foo2.magic() in bar(), but then you're repeating yourself (if the name of Foo2 changes, you'll have to remember to update that bar() method).

To me, this is a slight violation of the open/closed principle, since a decision made in Foo is impacting your ability to refactor common code in a derived class (ie it's less open to extension). If bar() were a classmethod we'd be fine:

class Foo(object):
    @classmethod
    def bar(cls):
        return "In Foo"

class Foo2(Foo):
    @classmethod
    def bar(cls):
        return "In Foo2 " + cls.magic()
    @classmethod
    def magic(cls):
        return "MAGIC"

print Foo2().bar()

Gives: In Foo2 MAGIC

@Rizwan Mumtaz 2016-09-20 09:03:29

I will try to explain the basic difference using an example.

class A(object):
    x = 0

    def say_hi(self):
        pass

    @staticmethod
    def say_hi_static():
        pass

    @classmethod
    def say_hi_class(cls):
        pass

    def run_self(self):
        self.x += 1
        print self.x # outputs 1
        self.say_hi()
        self.say_hi_static()
        self.say_hi_class()

    @staticmethod
    def run_static():
        print A.x  # outputs 0
        # A.say_hi() #  wrong
        A.say_hi_static()
        A.say_hi_class()

    @classmethod
    def run_class(cls):
        print cls.x # outputs 0
        # cls.say_hi() #  wrong
        cls.say_hi_static()
        cls.say_hi_class()

1 - we can directly call static and classmethods without initializing

# A.run_self() #  wrong
A.run_static()
A.run_class()

2- Static method cannot call self method but can call other static and classmethod

3- Static method belong to class and will not use object at all.

4- Class method are not bound to an object but to a class.

@Nathan Tregillus 2015-05-19 15:27:13

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.

@Cathal Garvey 2012-12-17 18:51:40

A quick hack-up ofotherwise identical methods in iPython reveals that @staticmethod yields marginal performance gains (in the nanoseconds), but otherwise it seems to serve no function. Also, any performance gains will probably be wiped out by the additional work of processing the method through staticmethod() during compilation (which happens prior to any code execution when you run a script).

For the sake of code readability I'd avoid @staticmethod unless your method will be used for loads of work, where the nanoseconds count.

@Keith Pinson 2012-12-17 19:46:51

"Otherwise seems to serve no function": not strictly true. See above discussion.

@Chris B. 2009-11-03 19:23:19

Official python docs:

@classmethod

A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:

class C:
    @classmethod
    def f(cls, arg1, arg2, ...): ... 

The @classmethod form is a function decorator – see the description of function definitions in Function definitions for details.

It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.

Class methods are different than C++ or Java static methods. If you want those, see staticmethod() in this section.

@staticmethod

A static method does not receive an implicit first argument. To declare a static method, use this idiom:

class C:
    @staticmethod
    def f(arg1, arg2, ...): ... 

The @staticmethod form is a function decorator – see the description of function definitions in Function definitions for details.

It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class.

Static methods in Python are similar to those found in Java or C++. For a more advanced concept, see classmethod() in this section.

@Terence Simpson 2008-09-25 21:07:06

Basically @classmethod makes a method whose first argument is the class it's called from (rather than the class instance), @staticmethod does not have any implicit arguments.

@Tom Neyland 2009-11-03 19:02:23

Here is a short article on this question

@staticmethod function is nothing more than a function defined inside a class. It is callable without instantiating the class first. It’s definition is immutable via inheritance.

@classmethod function also callable without instantiating the class, but its definition follows Sub class, not Parent class, via inheritance. That’s because the first argument for @classmethod function must always be cls (class).

@Mohan Gulati 2009-11-03 19:06:05

So does that mean that by using a staticmethod I am always bound to the Parent class and with the classmethod I am bound the class that I declare the classmethod in (in this case the sub class)?

@Matt Anderson 2009-11-03 19:18:30

No. By using a staticmethod you aren't bound at all; there is no implicit first parameter. By using classmethod, you get as implicit first parameter the class you called the method on (if you called it directly on a class), or the class of the instance you called the method on (if you called it on an instance).

@MestreLion 2012-05-03 10:01:46

Could be expanded a bit to show that, by having a class as a first argument, class methods have direct access to other class attributes and methods, while static methods do not (they would need to hardcode MyClass.attr for that)

@Armin Ronacher 2008-09-25 21:24:13

@staticmethod just disables the default function as method descriptor. classmethod wraps your function in a container callable that passes a reference to the owning class as first argument:

>>> class C(object):
...  pass
... 
>>> def f():
...  pass
... 
>>> staticmethod(f).__get__(None, C)
<function f at 0x5c1cf0>
>>> classmethod(f).__get__(None, C)
<bound method type.f of <class '__main__.C'>>

As a matter of fact, classmethod has a runtime overhead but makes it possible to access the owning class. Alternatively I recommend using a metaclass and putting the class methods on that metaclass:

>>> class CMeta(type):
...  def foo(cls):
...   print cls
... 
>>> class C(object):
...  __metaclass__ = CMeta
... 
>>> C.foo()
<class '__main__.C'>

@Armin Ronacher 2008-09-26 03:20:54

What's the problem with a metaclass?

@Daryl Spitzer 2009-01-18 17:51:28

What are the advantages to using a metaclass for this?

@Aaron Hall 2016-06-14 21:57:46

One possible downside of a metaclass for this that immediately occurs to me is that you can't call the classmethod directly on an instance. c = C(); c.foo() raises AttributeError, you'd have to do type(c).foo(). This might also be considered a feature - I can't think of why you'd want to though.

Related Questions

Sponsored Content

38 Answered Questions

[SOLVED] What does the "yield" keyword do?

20 Answered Questions

27 Answered Questions

12 Answered Questions

[SOLVED] Meaning of @classmethod and @staticmethod for beginner?

7 Answered Questions

[SOLVED] Understanding Python super() with __init__() methods

34 Answered Questions

[SOLVED] What is the difference between an interface and abstract class?

29 Answered Questions

[SOLVED] What does if __name__ == "__main__": do?

16 Answered Questions

[SOLVED] What are metaclasses in Python?

22 Answered Questions

[SOLVED] Difference between __str__ and __repr__?

7 Answered Questions

[SOLVED] What are the differences between type() and isinstance()?

Sponsored Content